matplotlib和pandas实现多y轴的多图形绘制
我们知道pandas支持次Y轴,但是将三次Y轴或者多Y轴放置在绘图上的方法应该是怎么样的呢。效果图与代码实现如下。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
ts = pd.Series(np.random.randn(1000),index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
df =pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
# df = pd.read_csv('d:\\pandas\\test.csv')
fig, ax = plt.subplots()
ax2, ax3 ,ax4 = ax.twinx(), ax.twinx() ,ax.twinx()
rspine = ax3.spines['right']
rspine.set_position(('axes', 1.125))
# ax3.set_frame_on(True)
ax3.patch.set_visible(False)
fig.subplots_adjust(right=0.75)
rspine = ax4.spines['right']
rspine.set_position(('axes', 1.25))
ax4.patch.set_visible(False)
fig.subplots_adjust(right=0.75)
df.A.plot(ax=ax, style='b-',legend=False)
df.B.plot(ax=ax2,style='r-',legend=False)
df.C.plot(ax=ax3, style='g-',legend=False)
df.D.plot(ax=ax4, style='k-',legend=False)
#设置图例,如果没有这行代码会使图例重叠
ax4.legend([ax.get_lines()[0], ax2.get_lines()[0], ax3.get_lines()[0],ax4.get_lines()[0]], ['A', 'B', 'C','D'],loc='best')
ax.set_xlabel("Time")
ax.set_ylabel('A',rotation=0)
ax2.set_ylabel('B',rotation=0)
ax3.set_ylabel('C',rotation=0)
ax4.set_ylabel('D',rotation=0)
ax.axhline(6, color="red", linestyle="--")
ax.axvline("2001-06-05", color="green", linestyle="--")
plt.title("test")
# 加这个两句 可以显示中文
plt.rcParams['font.sans-serif'] = [u'SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.show()