画一张招商银行2018年2月份每天的收盘价折线图和每日的涨跌幅柱状图,使用中文坐标。
#准备数据
list_tradedate=[
20180201,
20180202,
20180205,
20180206,
20180207,
20180208,
20180209,
20180212,
20180213,
20180214,
20180222,
20180223,
20180226,
20180227,
20180228
]
list_closeprice=[
34.45,
34.50,
34.89,
34.62,
32.39,
31.28,
30.71,
30.05,
30.91,
31.37,
31.50,
31.78,
31.51,
30.87,
30.30
]
list_growthrate=[
0.015027,
0.001451,
0.011304,
-0.007739,
-0.064414,
-0.034270,
-0.018223,
-0.021491,
0.028619,
0.014882,
0.004144,
0.008889,
-0.008496,
-0.020311,
-0.018465
]
软件系统中默认使用英文,要想使用中文标题、标注等需转换
#更改默认字体
from matplotlib.pylab import mpl
#指定默认字体,修改为雅黑
mpl.rcParams['font.sans-serif']=['SimHei']
#解决保存图像是负号‘-’显示为方块的问题
mpl.rcParams['axes.unicode_minus']=False
还需修改日期格式
# convert int to datetime
import datetime
list_tradedate2 = []
for trade_date in list_tradedate:
dt_tradedate = datetime.datetime.strptime(str(trade_date), '%Y%m%d')
list_tradedate2.append(dt_tradedate)
#导入Python画图库matplotlib
import matplotlib.pyplot as plt
#设置图画大小
fig=plt.figure(figsize=(12,8))
#画柱状图
ax1=fig.add_subplot(1,1,1)
ax1.bar(list_tradedate2,list_growthrate,label='每日涨跌幅')
ax1.legend(loc='upper left')
ax1.set_xlabel('日期')
ax1.set_ylabel('每日涨跌幅')
#画折线图
ax2=ax1.twinx()
ax2.plot(list_tradedate2,list_closeprice,color='red',label='每日收盘价')
ax2.legend(loc='upper right')
ax2.set_ylabel('每日收盘价')
ax2.set_ylim(0,40)
#标识标题及坐标轴信息
plt.title('招商银行2018年2月份每日收盘价/每日涨跌幅')
plt.legend()
#显示画图结果
plt.show()
注:计算机font文件中必须有要修改的中文字体样式,否则无法修改成功。
运行结果: