知识付费时代,经常接触到别人做得漂漂亮亮的数据动图,再配上抑扬顿挫的音乐,简直不要太高大上,自己学着做了下,原来这个动图做起来也没那么神秘
以下是动图的效果:
import xlrd
import matplotlib.pyplot as plt
import imageio
import numpy as np
def data_gif(cols, xlim_num, xlim_interval, duration,
title_attach=''): # cols 展示前几列的数据,xlim_num x轴刻度值,duration 两张图片间的间隔,建议写0.2-0.5,title_attach 标题后附加部分,可不写
frames = []
xlsx = xlrd.open_workbook('广州网签动图-200329.xlsx')
sheet = xlsx.sheet_by_index(0)
name_list = []
for j in range(1, sheet.ncols):
name_list.append(sheet.cell_value(0, j))
for i in range(1, sheet.nrows):
row_data_list = []
for j in range(1, sheet.ncols):
title = xlrd.xldate.xldate_as_datetime(sheet.cell(i, 0).value, 0).strftime('%Y-%m-%d')
row_data = sheet.cell_value(i, j)
row_data_list.append(int(row_data))
dic = dict(zip(name_list, row_data_list))
xy_sort = sorted(dic.items(), key=lambda d:d[1], reverse = False)
X_list = []
Y_list = []
for a in range(0, len(xy_sort)):
X_list.append(xy_sort[a][0])
Y_list.append(xy_sort[a][1])
font = {'family': 'SimHei',
'style': 'normal',
'weight': 'normal',
'color': '#FFFFFF',
'size': 20,
}
plt.rcParams['figure.figsize'] = (16.0, 9.0)
plt.rcParams['axes.facecolor'] = '#0D0434'
plt.rcParams['savefig.facecolor'] = '#0D0434'
plt.rcParams['xtick.color'] = '#FFFFFF'
plt.rcParams['ytick.color'] = '#FFFFFF'
plt.rcParams['axes.edgecolor'] = '#FFFFFF'
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.tick_params(labelsize=20)
plt.xlim((0, int(xlim_num)))
plt.xticks(range(0, xlim_num, xlim_interval))
# fig = plt.figure()
# ax = fig.add_subplot(111)
# ax.xaxis.label.set_color('red')
# ax.tick_params(axis='x', colors='red')
# ax.yaxis.label.set_color('red')
# ax.tick_params(axis='y', colors='red')
m = 0
for n in Y_list:
plt.text(int(xlim_num) / 10, m, str(n), ha='left', va='center', fontdict=font)
m += 1
plt.barh(X_list, Y_list, height=0.35, facecolor='#2C43C2', edgecolor='white')
plt.title(str(title) + str(title_attach), fontdict=font)
plt.savefig('%s.png' % str(title))
plt.close('all')
im = imageio.imread('%s.png' % str(title))
frames.append(im)
imageio.mimsave('data_gif.gif', frames, 'GIF', duration=round(duration, 2))
data_gif(11, 130, 10, 0.5, '广州新房网签')