matplotlib和pandas实现多y轴的多图形绘制

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()
  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值