简体   繁体   English

Plot 在 Python 和 Matplotlib 中有两个不同的 Y 轴

[英]Plot with Two Different Y-axis in Python with Matplotlib

Using the following code as an example i create a dataframe named dataset.使用以下代码作为示例,我创建了一个 dataframe 命名数据集。

value1 = np.random.random(100)*30
value2 = np.random.random(100)*30
value3 = np.random.random(100)*30
value4 = np.random.random(100)*1000

dataset = pd.DataFrame({'value1': value1, 'value2': value2, 'value3': value3, 'value4': value4}, columns=['value1', 'value2', 'value3', 'value4'])

dataset[['value1', 'value2', 'value3']].plot(figsize=(20,10), linewidth=2, fontsize = 20, grid=True, marker="o", label='a').legend(loc='upper center', bbox_to_anchor=(0.5, -0.12),
           ncol=12, prop={'size': 16});

dataset['value4'].plot(secondary_y=True, legend=True, linewidth=2, marker="o",)


plt.xlabel('Year',fontsize=20)
plt.ylabel('(b)',fontsize=20)

I plot this dataset on 2 axis but for some reason only the axis on the right is printed out but the left axis is not printing and am not sure why.我 plot 这个数据集在 2 轴上,但由于某种原因,只有右边的轴被打印出来,但左边的轴没有打印,我不知道为什么。

Secondly, am also trying to see how value1,2,3 respond to variable 4 (value4) so i would like the plot displayed as shown in the fig below.其次,我还试图查看 value1、2、3 如何响应变量 4 (value4),所以我希望 plot 显示如下图所示。 On the image we can see that we have variable 4 at the bottom of the graph and the rest at the top so we can clearly see how a rise or decline in variable 4 impacts variables 1,2,3.在图像上,我们可以看到图表底部有变量 4,顶部有 rest,因此我们可以清楚地看到变量 4 的上升或下降如何影响变量 1、2、3。 Currenly the display shows all all the variables mixed up but i would like it to look like the image below.目前显示屏显示所有混合变量,但我希望它看起来像下图。

Any assitance would be great, thanks任何帮助都会很棒,谢谢

在此处输入图像描述

Your code is correct.你的代码是正确的。 They are drawn on a range of two axes each.它们分别绘制在两个轴的范围内。 If you want to match it to your expected output, you can use ax1.set_ylim(-30,30) or ax 2.set_ylim(0,4000) .如果要将其与预期的 output 匹配,可以使用ax1.set_ylim(-30,30)ax 2.set_ylim(0,4000)

ax1 = dataset[['value1', 'value2', 'value3']].plot(figsize=(20,10),
                                             linewidth=2, fontsize = 20,
                                             grid=True, marker="o", label='a')
ax1.legend(loc='upper center', bbox_to_anchor=(0.5, -0.12), ncol=12, prop={'size': 16});

ax2 = dataset['value4'].plot(secondary_y=True,legend=True, linewidth=2, marker="o",)

ax1.set_ylim(-30,30)
ax2.set_ylim(0,4000)

ax1.set_xlabel('Year',fontsize=20)
ax2.set_ylabel('(b)',fontsize=20)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM