Python:带有辅助轴的 Suplots [英] Python: Suplots with secondary-axis

查看:39
本文介绍了Python:带有辅助轴的 Suplots的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的代码来做下图:

fig, ax = plt.subplots(figsize=(8, 6))ax.patch.set_facecolor('白色')ax.plot(df.index,df.X1.values,'b',标签="NMA",线宽= 1.5)ax.set_ylabel('索引')ax2 = ax.twinx()ax2.plot(df.index,df.Y.values,'r--',label='Rate', 线宽=1.5)ax2.set_ylabel('Rate')线 = ax.get_lines() + ax2.get_lines()lgd = ax.legend(lines, [line.get_label() for line in lines],loc ='lower center',ncol = 2,bbox_to_anchor =(0.5,-0.15),frameon = False)ax.set_title('经济利率和指数',重量=粗体")对于我在范围(5)中:plt.axvspan(Dates['Peak'][i],Dates['Trough'][i],facecolor='grey', alpha=0.5)plt.grid(假)plt.savefig('C:\\test.pdf',bbox_extra_artists = {lgd,),bbox_inches ='tight')

我很难在子图(2X2)中重现此图.在每个子图中,我唯一要更改的是蓝线(df 中的 X1...对于 X2、X3...).如何获得上图的 2X2 子图?当然,我只会在子图的底部保留一个图例.感谢您的帮助.

数据是

I wrote the following code below to do the following graph:

fig, ax = plt.subplots(figsize=(8, 6))
ax.patch.set_facecolor('white')
ax.plot(df.index, df.X1.values, 'b',
        label='NMA', linewidth=1.5)
ax.set_ylabel('Index')
ax2 = ax.twinx()
ax2.plot(df.index, df.Y.values, 'r--',
         label='Rate', linewidth=1.5)
ax2.set_ylabel('Rate')
lines = ax.get_lines() + ax2.get_lines()
lgd = ax.legend(lines, [line.get_label() for line in lines],
                loc='lower center', ncol=2, bbox_to_anchor=(0.5, -0.15),
                frameon=False)
ax.set_title('Economic Rate and Index',
             weight='bold')
for i in range(5):
    plt.axvspan(Dates['Peak'][i], Dates['Trough'][i],
                facecolor='grey', alpha=0.5)
plt.grid(False)
plt.savefig('C:\\test.pdf',
            bbox_extra_artists=(lgd,), bbox_inches='tight')

I am having a hard time to reproduce this figure in a subplot (2X2). The only thing I would change in each of the subplots is the blue line (X1 in df... for X2, X3...). How can I have a 2X2 subplot of the above graph? Of Course I would only keep one legend at the bottom of the subplots. Thanks for the help.

The data is here and the "Dates" to reproduce the gray bars here.

解决方案

This is how you could create a 2x2 raster with twinx each:

import matplotlib.pyplot as plt

fig, ((ax1a, ax2a), (ax3a, ax4a)) = plt.subplots(2, 2)

ax1b = ax1a.twinx()
ax2b = ax2a.twinx()
ax3b = ax3a.twinx()
ax4b = ax4a.twinx()

ax1a.set_ylabel('ax1a')
ax2a.set_ylabel('ax2a')
ax3a.set_ylabel('ax3a')
ax4a.set_ylabel('ax4a')
ax1b.set_ylabel('ax1b')
ax2b.set_ylabel('ax2b')
ax3b.set_ylabel('ax3b')
ax4b.set_ylabel('ax4b')

plt.tight_layout()
plt.show()

Result:

这篇关于Python:带有辅助轴的 Suplots的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆