条形码(种类)没有显示正确的图(matplotlib)

问题描述 投票:0回答:1

我需要使用三个变量做一个情节。其中一个应该在bar格式(种类)的次要Y轴上,其余变量(两个)应该使用简单的线在左轴上。但是,我得到了以下图表:

enter image description here

当我使用line格式的三个变量时,我得到了正确的图(这对于视觉分析来说不是很有用):enter image description here

我使用我的数据中的一个小样本(下面的代码)进行了快速测试。当我使用bar格式为第三个时,我得到了正确的图片。 enter image description here

我想知道,发生了什么事?数据大小是否有问题(我不认为这样bcs我得到的行数少于100行)?

df2 = pd.DataFrame({'ind':[120.29, 125.45, 127.37, 130.39, 128.30], 
                    'var1':[129.907990, 129.571185, 129.234380, 128.897574, 128.560769], 
                    'var2':[-0.074037, -0.031806, -0.014426, 0.011578, -0.002028]})

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
df2['ind'].plot(ax=ax1)
df2['var1'].plot(ax=ax1)
df2['var2'].plot(kind='bar', ax=ax2, color='r')
plt.show()

PD:另外,我注意到在第三张照片中,线条位于条形图后面。我怎么能改变呢?

python-3.x matplotlib axis2
1个回答
1
投票

我找到了解决方案(这个link帮了我很多)。基本上,它基于您之前设置的索引。

这是新代码:

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(df2.index, df2['ind']) 
ax1.plot(df2.index, df2['var1'])
ax2.bar(df2.index, df2['var2'], color='r')
plt.show()

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.