https://matplotlib.org/tutorials/intermediate/legend_guide.html
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np
%matplotlib inline
plt.rcParams['font.sans-serif'] = ['SimHei']#显示中文
plt.style.use('ggplot')
# 生成数据
month = np.linspace(1, 12, 12)
dau = np.random.randint(200, 300, 12)
ctr = np.random.randint(8, 20, 12) / 100
# 画图
fig, ax1 = plt.subplots(figsize = (10, 5), facecolor='white')
# 左轴
ax1.bar(month, dau, color='g', alpha=0.5,label="日活(万)")
ax1.set_xlabel('月份')
ax1.set_ylabel('日活(万)')
ax1.legend(loc='upper left')
# 右轴
ax2 = ax1.twinx()
ax2.plot(month, ctr, '-or',label='点击率')
ax2.set_ylabel('点击率')
ax2.set_ylim(0, 0.2)
ax2.legend(loc='upper right')
# 将点击率坐标轴以百分比格式显示
def to_percent(temp, position):
return '%2.1f'%(100*temp) + '%'
plt.gca().yaxis.set_major_formatter(FuncFormatter(to_percent))
# 标题
plt.title('2017年XXX日活及点击率趋势')
plt.show()
网友评论