python的matplotlib绘图(双坐标轴)
python的matplotlib绘图(双坐标轴)
绘制图形如下:
代码如下:
import pandas as pd
import matplotlib.pyplot as plt
from pylab import mpl
###读取文件
df=pd.read_excel('file')
###创建画布和绘图区域
fig = plt.figure(figsize=(10,6))
ax1 = fig.add_subplot(111)
###使图像中的文字正常显示
mpl.rcParams['font.sans-serif']=['Microsoft YaHei']
###绘图
ax1.bar(d['A'],d['B'],linewidth=2,label='B',color='Black')
ax1.bar(d['A'],d['C'],linewidth=2,label='C',color='red')
ax2=ax1.twinx()
ax2.plot(d['A'],d['D'],linewidth=2,label='D',color='B')
###添加图例
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
####添加X,Y坐标轴
ax1.set_xlabel("Hour")
ax1.set_ylabel("B、C,(μg/m^3)")
ax2.set_ylabel("OC/EC")
####添加标题
###设置坐标轴范围
ax2.set_ylim(0, 2)
ax1.set_ylim(0,200)
####设置坐标轴X的间隔及显示字体大小
plt.xticks([0,2,4,6,8,10,12,14,16,18,20,22],fontsize=20)
####保存文件
plt.savefig('***02.jpg')
plt.show()
matplotlib官方文档:
https://matplotlib.org/index.html
原文链接
python的matplotlib绘图(双坐标轴)_python 画两条横坐标不同的线_Xinrui__的博客-CSDN博客