首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在matplotlib中用两轴绘制三类

在matplotlib中用两轴绘制三类
EN

Stack Overflow用户
提问于 2018-10-15 21:18:34
回答 1查看 150关注 0票数 1

我使用熊猫和matplotlib的组合来绘制几个类别的三个值。我希望有一个图解有自己的轴线,而另两个则共享一个轴。

关闭,但说明了为什么我需要双轴:

代码语言:javascript
复制
pd.DataFrame([[1,2,3], [500,600,700], [500, 700, 650]], columns=['foo', 'bar','baz'],
             index=['a','b','c']).T.plot(kind='bar')

相反,我想要a条的第二个轴。我的尝试:

代码语言:javascript
复制
smol = pd.DataFrame([[1,2,3], [500,600,700], [500, 700, 650]], columns=['foo', 'bar','baz'],
        index=['a','b','c']).T

fig = plt.figure(figsize=(10,5)) # Create matplotlib figure

ax = fig.add_subplot(111) # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax.

smol['a'].plot(kind='bar', color='red', ax=ax, width=0.3, 
                    position=1, edgecolor='black')
smol['b'].plot(kind='bar', color='blue', ax=ax2, width=0.3, 
                 position=0, edgecolor='black')

ax.set_ylabel('Small scale')
ax2.set_ylabel('Big scale')

plt.show()

不幸的是,添加

代码语言:javascript
复制
smol['c'].plot(kind='bar', color='green', ax=ax2, width=0.3, 
                 position=0, edgecolor='black') 

生产:

我怎么能让bc共享一个轴,但是像第一次尝试时那样出现在彼此旁边呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-15 21:49:37

我使用过secondary_y关键字。代码也短得多。

代码语言:javascript
复制
smol = pd.DataFrame([[1,2,3], [500,600,700], [500, 700, 650]], columns=['foo', 'bar','baz'],
        index=['a','b','c']).T

ax = smol.plot(kind="bar", secondary_y=['b', 'c'])

ax.set_ylabel('Small scale')
ax.right_ax.set_ylabel('Big scale')

plt.show()

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52824897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档