【问题标题】:Plotting in Pandas with columns that have different scales在 Pandas 中绘制具有不同比例的列
【发布时间】:2020-09-30 15:49:40
【问题描述】:

所以我试图绘制一个看起来像这样的数据集:

cat    a        b        c
idk    0.47     0.58     1.17
yeet   0.38     0.11     -0.8
skeet  0.03     0.14     0.46

基本上,cat 是一个分类变量,a 和 b 是在 [0,1] 范围内的变量,而 c 是在 [-7,7] 范围内的变量,我想要一个 x 轴的图是分类变量,左y轴为[0,1]对应a&b,右y轴对应c。

我可以用相同的 y 轴绘制所有这些,这显然不是理想的,并且试图用

绘制不同的 y 轴

fig = plt.figure() 
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx() 
width = 0.4
wisco_ill_succ.plot.bar(x='cat', y=['a','b'], ax = ax1, position = 0, width = width)
wisco_ill_succ.plot.bar(x='cat', y=['c'], ax = ax2, position = 1, width = width)

我得到了我想要的,但是 x 轴没有对齐,看起来就像一团乱麻:

我查看了这个Pandas: Bar-Plot with two bars and two y-axis,但坦率地说,它并没有太大帮助。有什么我可以做的吗?或者我应该把它分成两个不同的图表吗?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您可以使用secondary_y 参数:

    ax = df.plot.bar(secondary_y=['c'], x='cat', rot=0)
    ax.set_ylim(-1,1)
    ax.right_ax.set_ylim(-7,7)
    

    【讨论】:

    • 这对我有用。非常简单的编码。请注意,您必须同时运行三行,当我逐行测试时不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2019-04-17
    • 2021-05-07
    • 2012-06-13
    • 1970-01-01
    相关资源
    最近更新 更多