一款Python工具制作的動態(tài)條形圖(強(qiáng)烈推薦!)
前言
大家好,說起動態(tài)條形圖,之前推薦過兩個(gè) Python 庫,比如Bar Chart Race、Pandas_Alive,都可以實(shí)現(xiàn)。今天就給大家再介紹一個(gè)新更加棒的工具。


這款新的Python庫pynimate,一樣可以制作動態(tài)條形圖,而且樣式更好看。
GitHub地址:
https://github.com/julkaar9/pynimate
文檔地址:https://julkaar9.github.io/pynimate/
方法如下
首先使用pip安裝這個(gè)庫,注意Python版本要大于等于3.9。
# 安裝pynimate pip install pynimate -i https://pypi.tuna.tsinghua.edu.cn/simple
其中pynimate使用pandas數(shù)據(jù)幀格式,時(shí)間列設(shè)置為索引index。
time, col1, col2, col3 2012 1 2 1 2013 1 1 2 2014 2 1.5 3 2015 2.5 2 3.5
然后來看兩個(gè)官方示例。
第一個(gè)示例比較簡單,代碼如下。
from matplotlib import pyplot as plt
import pandas as pd
import pynimate as nim
# 數(shù)據(jù)格式+索引
df = pd.DataFrame(
{
"time": \["1960-01-01", "1961-01-01", "1962-01-01"\],
"Afghanistan": \[1, 2, 3\],
"Angola": \[2, 3, 4\],
"Albania": \[1, 2, 5\],
"USA": \[5, 3, 4\],
"Argentina": \[1, 4, 5\],
}
).set\_index("time")
# Canvas類是動畫的基礎(chǔ)
cnv = nim.Canvas()
# 使用Barplot模塊創(chuàng)建一個(gè)動態(tài)條形圖, 插值頻率為2天
bar = nim.Barplot(df, "%Y-%m-%d", "2d")
# 使用了回調(diào)函數(shù), 返回以月、年為單位格式化的datetime
bar.set\_time(callback=lambda i, datafier: datafier.data.index\[i\].year)
# 將條形圖添加到畫布中
cnv.add\_plot(bar)
cnv.animate()
plt.show()
Canvas類是動畫的基礎(chǔ),它會處理matplotlib圖、子圖以及創(chuàng)建和保存動畫。
Barplot模塊創(chuàng)建動態(tài)條形圖,有三個(gè)必傳參數(shù),data、time_format、ip_freq。
分別為數(shù)據(jù)、時(shí)間格式、插值頻率(控制刷新頻率)。
效果如下,就是一個(gè)簡單的動態(tài)條形圖。

我們還可以將結(jié)果保存為GIF或者是mp4,其中mp4需要安裝ffmpeg。
# 保存gif, 1秒24幀
cnv.save("file", 24, "gif")
# 電腦安裝好ffmpeg后, 安裝Python庫
pip install ffmpeg-python
# 保存mp4, 1秒24幀
cnv.save("file", 24 ,"mp4")
第二個(gè)示例相對復(fù)雜一些,可以自定義參數(shù),樣式設(shè)置成深色模式。
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import pynimate as nim
# 更新條形圖
def post\_update(ax, i, datafier, bar\_attr):
ax.spines\["top"\].set\_visible(False)
ax.spines\["right"\].set\_visible(False)
ax.spines\["bottom"\].set\_visible(False)
ax.spines\["left"\].set\_visible(False)
ax.set\_facecolor("#001219")
for bar, x, y in zip(
bar\_attr.top\_bars,
bar\_attr.bar\_length,
bar\_attr.bar\_rank,
):
ax.text(
x - 0.3,
y,
datafier.col\_var.loc\[bar, "continent"\],
ha="right",
color="k",
size=12,
)
# 讀取數(shù)據(jù)
df = pd.read\_csv("sample.csv").set\_index("time")
# 分類
col = pd.DataFrame(
{
"columns": \["Afghanistan", "Angola", "Albania", "USA", "Argentina"\],
"continent": \["Asia", "Africa", "Europe", "N America", "S America"\],
}
).set\_index("columns")
# 顏色
bar\_cols = {
"Afghanistan": "#2a9d8f",
"Angola": "#e9c46a",
"Albania": "#e76f51",
"USA": "#a7c957",
"Argentina": "#e5989b",
}
# 新建畫布
cnv = nim.Canvas(figsize=(12.8, 7.2), facecolor="#001219")
bar = nim.Barplot(
df, "%Y-%m-%d", "3d", post\_update=post\_update, rounded\_edges=True, grid=False
)
# 條形圖分類
bar.add\_var(col\_var=col)
# 條形圖顏色
bar.set\_bar\_color(bar\_cols)
# 標(biāo)題設(shè)置
bar.set\_title("Sample Title", color="w", weight=600)
# x軸設(shè)置
bar.set\_xlabel("xlabel", color="w")
# 時(shí)間設(shè)置
bar.set\_time(
callback=lambda i, datafier: datafier.data.index\[i\].strftime("%b, %Y"), color="w"
)
# 文字顯示
bar.set\_text(
"sum",
callback=lambda i, datafier: f"Total :{np.round(datafier.data.iloc\[i\].sum(),2)}",
size=20,
x=0.72,
y=0.20,
color="w",
)
# 文字顏色設(shè)置
bar.set\_bar\_annots(color="w", size=13)
bar.set\_xticks(colors="w", length=0, labelsize=13)
bar.set\_yticks(colors="w", labelsize=13)
# 條形圖邊框設(shè)置
bar.set\_bar\_border\_props(
edge\_color="black", pad=0.1, mutation\_aspect=1, radius=0.2, mutation\_scale=0.6
)
cnv.add\_plot(bar)
cnv.animate()
# 顯示
# plt.show()
# 保存gif
cnv.save("example3", 24, "gif")
效果如下,可以看出比上面的簡單示例好看了不少。

另外作者還提供了相關(guān)的接口文檔。
幫助我們理解學(xué)習(xí),如何去自定義參數(shù)設(shè)置。
包含畫布設(shè)置、保存設(shè)置、條形圖設(shè)置、數(shù)據(jù)設(shè)置等等。

下面我們就通過獲取電視劇狂飆角色的百度指數(shù)數(shù)據(jù),來制作一個(gè)動態(tài)條形圖。
先對網(wǎng)頁進(jìn)行分析,賬號登陸百度指數(shù),搜索關(guān)鍵詞「高啟強(qiáng)」,查看數(shù)據(jù)情況。

發(fā)現(xiàn)數(shù)據(jù)經(jīng)過js加密,所以需要對獲取到的數(shù)據(jù)進(jìn)行解析。
使用了一個(gè)開源的代碼,分分鐘就搞定數(shù)據(jù)問題。
具體代碼如下,其中「cookie值」需要替換成你自己的。
import datetime
import requests
import json
word\_url = 'http://index.baidu.com/api/SearchApi/thumbnail?area=0&word={}'
def get\_html(url):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36",
"Host": "index.baidu.com",
"Referer": "http://index.baidu.com/v2/main/index.html",
"Cipher-Text": "1652425237825\_1652501356206\_VBpwl9UG8Dvs2fAi91KToRTSAP7sDsQU5phHL97raPDFJdYz3fHf9hBAQrGGCs+qJoP7yb44Uvf91F7vqJLVL0tKnIWE+W3jXAI30xx340rhcwUDQZ162FPAe0a1jsCluJRmMLZtiIplubGMW/QoE/0Pw+2caH39Ok8IsudE4wGLBUdYg1/bKl4MGwLrJZ7H6wbhR0vT5X0OdCX4bMJE7vcwRCSGquRjam03pWDGZ51X15fOlO0qMZ2kqa3BmxwNlfEZ81l3L9nZdrc3/Tl4+mNpaLM7vA5WNEQhTBoDVZs6GBRcJc/FSjd6e4aFGAiCp1Y8MD66chTiykjIN51s7gbJ44JfVS0NjBnsvuF55bs="
}
cookies = {
'Cookie': 你的cookie
}
response = requests.get(url, headers=headers, cookies=cookies)
return response.text
def decrypt(t, e):
n = list(t)
i = list(e)
a = {}
result = \[\]
ln = int(len(n) / 2)
start = n\[ln:\]
end = n\[:ln\]
for j, k in zip(start, end):
a.update({k: j})
for j in e:
result.append(a.get(j))
return ''.join(result)
def get\_ptbk(uniqid):
url = 'http://index.baidu.com/Interface/ptbk?uniqid={}'
resp = get\_html(url.format(uniqid))
return json.loads(resp)\['data'\]
def get\_data(keyword, start='2011-01-02', end='2023-01-02'):
url = "https://index.baidu.com/api/SearchApi/index?area=0&word=\[\[%7B%22name%22:%22{}%22,%22wordType%22:1%7D\]\]&startDate={}&endDate={}".format(keyword, start, end)
data = get\_html(url)
data = json.loads(data)
uniqid = data\['data'\]\['uniqid'\]
data = data\['data'\]\['userIndexes'\]\[0\]\['all'\]\['data'\]
ptbk = get\_ptbk(uniqid)
result = decrypt(ptbk, data)
result = result.split(',')
start = start\_date.split("-")
end = end\_date.split("-")
a = datetime.date(int(start\[0\]), int(start\[1\]), int(start\[2\]))
b = datetime.date(int(end\[0\]), int(end\[1\]), int(end\[2\]))
node = 0
for i in range(a.toordinal(), b.toordinal()):
date = datetime.date.fromordinal(i)
print(date, result\[node\])
node += 1
with open('data.csv', 'a+') as f:
f.write(keyword + ',' + date.strftime('%Y-%m-%d') + ',' + result\[node\] + '\\n')
if \_\_name\_\_ == '\_\_main\_\_':
names = \['唐小龍', '孟德海', '孟鈺', '安欣', '安長林', '徐忠', '徐江', '曹闖', '李響', '李宏偉', '李有田', '楊健', '泰叔', '趙立冬', '過山峰', '陸寒', '陳書婷', '高啟蘭', '高啟強(qiáng)', '高啟盛', '高曉晨'\]
for keyword in names:
start\_date = "2023-01-14"
end\_date = "2023-02-04"
get\_data(keyword, start\_date, end\_date)
爬取數(shù)據(jù)情況如下,一共是400多條,其中有空值存在。
然后就是轉(zhuǎn)換成pynimate所需的數(shù)據(jù)格式。

對數(shù)據(jù)進(jìn)行數(shù)據(jù)透視表操作,并且將空值數(shù)據(jù)填充為0。
import pandas as pd
# 讀取數(shù)據(jù)
df = pd.read\_csv('data.csv', encoding='utf-8', header=None, names=\['name', 'day', 'number'\])
# 數(shù)據(jù)處理,數(shù)據(jù)透視表
df\_result = pd.pivot\_table(df, values='number', index=\['day'\], columns=\['name'\], fill\_value=0)
# 保存
df\_result.to\_csv('result.csv')
保存文件,數(shù)據(jù)情況如下。

使用之前深色模式的可視化代碼,并略微修改。
比如設(shè)置條形圖數(shù)量(n_bars)、標(biāo)題字體大小及位置、中文顯示等等。
from matplotlib import pyplot as plt
import pandas as pd
import pynimate as nim
# 中文顯示
plt.rcParams\['font.sans-serif'\] = \['SimHei'\] #Windows
plt.rcParams\['font.sans-serif'\] = \['Hiragino Sans GB'\] #Mac
plt.rcParams\['axes.unicode\_minus'\] = False
# 更新條形圖
def post\_update(ax, i, datafier, bar\_attr):
ax.spines\["top"\].set\_visible(False)
ax.spines\["right"\].set\_visible(False)
ax.spines\["bottom"\].set\_visible(False)
ax.spines\["left"\].set\_visible(False)
ax.set\_facecolor("#001219")
# 讀取數(shù)據(jù)
df = pd.read\_csv("result.csv").set\_index("day")
# 新建畫布
cnv = nim.Canvas(figsize=(12.8, 7.2), facecolor="#001219")
bar = nim.Barplot(
df, "%Y-%m-%d", "3h", post\_update=post\_update, rounded\_edges=True, grid=False, n\_bars=6
)
# 標(biāo)題設(shè)置
bar.set\_title("《狂飆》主要角色熱度排行(百度指數(shù))", color="w", weight=600, x=0.15, size=30)
# 時(shí)間設(shè)置
bar.set\_time(
callback=lambda i, datafier: datafier.data.index\[i\].strftime("%Y-%m-%d"), color="w", y=0.2, size=20
)
# 文字顏色設(shè)置
bar.set\_bar\_annots(color="w", size=13)
bar.set\_xticks(colors="w", length=0, labelsize=13)
bar.set\_yticks(colors="w", labelsize=13)
# 條形圖邊框設(shè)置
bar.set\_bar\_border\_props(
edge\_color="black", pad=0.1, mutation\_aspect=1, radius=0.2, mutation\_scale=0.6
)
cnv.add\_plot(bar)
cnv.animate()
# 顯示
# plt.show()
# 保存gif
cnv.save("kuangbiao", 24, "gif")
執(zhí)行代碼,《狂飆》電視劇角色熱度排行的動態(tài)條形圖就制作好了。
結(jié)果如下,看著還不錯(cuò)。

總結(jié)
到此這篇關(guān)于Python工具制作的動態(tài)條形圖的文章就介紹到這了,更多相關(guān)Python動態(tài)條形圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
TensorFlow實(shí)現(xiàn)簡單卷積神經(jīng)網(wǎng)絡(luò)
這篇文章主要為大家詳細(xì)介紹了TensorFlow實(shí)現(xiàn)簡單卷積神經(jīng)網(wǎng)絡(luò),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05
使用Python與MQTT實(shí)現(xiàn)異步通信功能
物聯(lián)網(wǎng)(IoT)和實(shí)時(shí)通信的世界中,消息隊(duì)列遙測傳輸(MQTT)協(xié)議因其輕量級、可靠性和實(shí)時(shí)性成為廣受歡迎的選擇,本文給大家介紹了使用Python與MQTT實(shí)現(xiàn)異步通信功能,需要的朋友可以參考下2024-12-12
Python+Pyecharts實(shí)現(xiàn)散點(diǎn)圖的繪制
散點(diǎn)圖是指在回歸分析中,數(shù)據(jù)點(diǎn)在直角坐標(biāo)系平面上的分布圖,散點(diǎn)圖表示因變量隨自變量而變化的大致趨勢,據(jù)此可以選擇合適的函數(shù)對數(shù)據(jù)點(diǎn)進(jìn)行擬合。本文將利用Python Pyecharts實(shí)現(xiàn)散點(diǎn)圖的繪制,需要的可以參考一下2022-06-06
python登陸asp網(wǎng)站頁面的實(shí)現(xiàn)代碼
這篇文章主要介紹了python登陸asp網(wǎng)站頁面的實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-01-01
在python里使用await關(guān)鍵字來等另外一個(gè)協(xié)程的實(shí)例
這篇文章主要介紹了在python里使用await關(guān)鍵字來等另外一個(gè)協(xié)程的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05

