超简单,百行Python代码制作动态条形图跳舞
Python与算法之美
共 6558字,需浏览 14分钟
·
2021-05-25 23:34
打码不易,不想被白嫖,有需要完整代码和GDP数据集的同学,可以对本文点赞,在看,和分享后在公众号“算法美食屋”后台回复关键字:动态图,添加作者微信获取。感谢支持。😊
先上图片:
再上视频:
最后上代码:
import numpy as np
import pandas as pd
import matplotlib as mpl
from matplotlib import pyplot as plt
import matplotlib.animation as animation
import imageio
import os
import cv2
from PIL import Image
cmap = [
'#2E91E5',
'#1CA71C',
'#DA16FF',
'#B68100',
'#EB663B',
'#00A08B',
'#FC0080',
'#6C7C32',
'#862A16',
'#620042',
'#DA60CA',
'#0D2A63']*100
def bar_chart_dance(df,filename = None,title = "",figsize = (6,3.5),dpi = 144,duration = 2):
assert filename is None or filename.endswith(".html"), "filename should like *.html!"
fig,ax = plt.subplots(figsize=figsize,dpi=dpi)
ax.set_facecolor("0.9")
# 调整spines
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["bottom"].set_visible(False)
def plot_frame(i):
# 添加文本
ax.clear()
ax.set_title(title)
ax.text(0.05,0.85,f"{df.iloc[i-1,0]}:{df.iloc[i-1,1]}",
transform = ax.transAxes, ha = "left")
if i <8:
xdata = df.iloc[0:i,0].tolist()
ydata = df.iloc[0:i,1].tolist()
colors = cmap[0:i]
ax.bar(xdata,ydata,color =colors,zorder = 4)
plt.xticks(range(8),xdata,horizontalalignment = "center",rotation = 0)
values = df.iloc[:8,1].values
ylim = (values.min(),values.max())
ax.set_ylim(ymin = ylim[0]-(ylim[1]-ylim[0])/10,ymax = ylim[1]+(ylim[1]-ylim[0])/10)
ax.set_xlim(xmin = -0.6,xmax = 6.6)
ax.tick_params(bottom = False,left = False,labelsize = 8,direction = "in",length = 2)
else:
xdata = df.iloc[i-7:i,0].tolist()
ydata = df.iloc[i-7:i,1].tolist()
colors = cmap[i-7:i]
ax.bar(xdata,ydata,color =colors)
plt.xticks(range(8),xdata,horizontalalignment = "center",rotation = 0)
values = df.iloc[i-7:i,1].values
ylim = (values.min(),values.max())
ax.set_ylim(ymin = ylim[0]-(ylim[1]-ylim[0])/10,ymax = ylim[1]+(ylim[1]-ylim[0])/10)
ax.set_xlim(xmin = -0.6,xmax = 6.6)
ax.tick_params(bottom = False,left = False,labelsize = 8,direction = "in",length = 2)
my_animation = animation.FuncAnimation(fig,plot_frame,frames = range(1,len(df)+1),interval = int(duration*1000))
if filename is None:
try:
from IPython.display import HTML
HTML(my_animation.to_jshtml())
return HTML(my_animation.to_jshtml())
except ImportError:
pass
else:
my_animation.save(filename)
return filename
df = pd.read_csv("./data/gdp_china_2019.csv")
df = df[["省份","人均GDP"]].sort_values("人均GDP")
df["省份"] = [x if "自治区" not in x else x[0:2] for x in df["省份"]]
df["人均GDP"] = [int(x) for x in df["人均GDP"]]
df.index = range(len(df))
html_file = "bar_chart_dance.html"
bar_chart_dance(df,filename = html_file,title = "中国大陆各省市2019人均GDP(人民币)")
主要思路是构建plot_frame函数逐帧绘制图像,再用matplotlib的animation模块制作动画。
收工。😋
打码不易,不想被白嫖,有需要完整代码和GDP数据集的同学,可以对本文点赞,在看,和分享后在公众号“算法美食屋”后台回复关键字:动态图,添加作者微信获取。感谢支持。😊
评论