繪製自動電影票房變化圖製作b站同款自動動態更新柱狀圖

今天給大家準備的是動態更新的動態圖,上次在b站見到了,便想着來做,正好又在豬哥的公號看到了這個知識點,就馬不停蹄的我就開始練習,下面是效果圖。
材料: python3
matplotlib
數據獲取地址:http://piaofang.maoyan.com/dashboard?movieId=1277644貓眼電影票房。

在這裏插入圖片描述
首先進行數據的獲取,接口很容易找,看到點擊下一天並不會出現網址我們就可以知道是動態獲取的網頁。找到json接口後我們對它進行所需數據的獲取便可。
在這裏插入圖片描述
之後因爲我們需要的是多天的票房數據,所以我們也需要對url地址進行遍歷,最後再將獲取的數據保存下來以便後續處理。
獲取數據的代碼如下

url_lst = []
for i in range(19):
    url = 'http://piaofang.maoyan.com/second-box?beginDate='+str(int(20191201+i))
    url_lst.append(url)
def use_url(url,time):
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
    }
    res = requests.get(url=url,headers=headers)
    res.encoding='utf-8'
    data = res.json()
    dict = []
    for i in data['data']['list']:
        dic = {}
        dic['電影']=i['movieName']
        dic['票房']=i['boxInfo']
        dic['日期'] = time
        dict.append(dic)
    return dict
data_lst = []
time = 20191201
for j in url_lst:
    data_lst.extend(use_url(j,time))
    time+=1
df_result = pd.DataFrame(data_lst)
print(df_result)
df_result.to_csv(r'票房.csv',encoding='utf-8')#導入到excel文件

數據獲取好後我們就可以開始準備畫圖處理啦,我這裏選取了幾個電影做例子。

df = pd.read_csv('E:\pythonlian1\票房.csv',encoding="gbk")
df1=df[(df['日期']>=20191205)&(df['電影']=='冰雪奇緣2')|(df['電影']=='誤殺')|(df['電影']=='冰雪奇緣2')|(df['電影']=='中國機長')|(df['電影']=='勇敢者遊戲2:再戰巔峯')]
print(df1)

在這裏插入圖片描述
然後準備好各行的顏色分配

colors = dict(zip(
    dff['電影'],
    ['#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#cccc4d',
     '#aafbff', '#f7bb5f', '#eafb50', '#ffb3e6', '#4169e1']
))
print(colors)

我們直接先畫出靜態的圖表
代碼部分也只是照貓畫虎,去除邊框加上線條,設置字體位置與大小,再配上顏色

fig, ax = plt.subplots(figsize=(15, 8))
def draw_barchart(year):
    dff = df1[df1['日期'].eq(year)].sort_values(by='票房', ascending=True).tail(10)
    ax.clear()
    ax.barh(dff['電影'], dff['票房'], color=[colors[x] for x in dff['電影']])
    for i, (value, name) in enumerate(zip(dff['票房'], dff['電影'])):
        ax.text(value, i,     name,           size=14, weight=600, ha='right', va='bottom')
        ax.text(value, i,     f'{value:,.0f}',  size=14, ha='left',  va='center')
    ax.text(1, 0.4, year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800)
    ax.text(0, 1.06, '票房數量', transform=ax.transAxes, size=12, color='#777777')
    ax.xaxis.set_ticks_position('top')
    ax.set_yticks([])
    ax.margins(0, 0.01)
    ax.grid(which='major', axis='x', linestyle='-')#線條佈置
    ax.set_axisbelow(True)
    ax.text(0, 1.12, '票房變化',
            transform=ax.transAxes, size=24, weight=600, ha='left')
    plt.box(False)   #是否帶邊框
draw_barchart(20191219)

對於動圖的繪製,我們可以使用matplotlib中的animation,配置幾個參數傳入之前靜態圖的函數中就可以了

import matplotlib.animation as animation
from IPython.display import HTML
fig, ax = plt.subplots(figsize=(15, 8))
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(20191202, 20191219))
HTML(animator.to_jshtml()) 

大功告成,成品就會同開始的那幅圖一樣,它有好幾個參數可以設置,比如這裏沒添加的幀數之類,可參考https://www.cnblogs.com/zhouzhe-blog/p/9614360.html
大家可以看看。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章