【问题标题】:Python Pandas plots layer order changed by secondary_yPython Pandas 绘制由 secondary_y 更改的图层顺序
【发布时间】:2017-04-14 05:52:28
【问题描述】:

我正在尝试将折线图和条形图合并为一个图。数据源是 pandas 数据框。

这是一个演示:

import pandas as pd
test = {"index": range(10), 
        "line": [i**2 for i in range(10)], 
        "bar": [i*10 for i in range(10)]}
test=pd.DataFrame(test)
ax=test.plot(x="index",y="line")
test.plot(x="index",y="bar",color="r",kind="bar",ax=ax)

到目前为止一切都很好,您可以看到线条在条形上方。如果我通过将最后一行更改为使用右侧的辅助 y 轴来询问条形图:

test.plot(x="index",y="bar",color="r",kind="bar",ax=ax, secondary_y=True)

然后条形图将出现在我不想要的行的顶部。

这是两个图:

我尝试先绘制条形图,然后绘制线条,我还尝试使用zorder 强制线条上方的线条,但它们都不起作用。

任何建议或帮助将不胜感激。

【问题讨论】:

  • 您使用的 zorder 值是多少?我发现有时我需要将它设置得非常大才能获得我想要的效果(例如,条形图的每个元素都有自己的 z 设置,所以要让线条在顶部,你需要使用大于 30 的东西)
  • 另外,你需要使用secondary_y吗?如果您只想获取右侧的轴标签,还有其他方法。
  • 嗨,戈登,谢谢您的帮助。在我的实际情况下,条形高度实际上远高于线值。所以我认为直接的方法是使用secondary_y。
  • 另外,我将zorder 设置为 1000 用于线,0 用于条,但没有运气。

标签: python pandas matplotlib


【解决方案1】:

第二个坐标轴总是在第一个坐标轴之上。因此,您需要最后绘制线图以使其显示在条形图的顶部。 您可以考虑以下解决方案,将线设置为二级刻度:

import pandas as pd
test = {"index": range(10), 
        "line": [i**2 for i in range(10)], 
        "bar": [100*i*10 for i in range(10)]}
test=pd.DataFrame(test)

ax  = test.plot(x="index",y="bar",color="r",kind="bar")
ax2 = test.plot(x="index",y="line", color="b", ax=ax, secondary_y=True)
ax.set_ylabel("bar", color="r")
ax2.set_ylabel("line", color="b")

如果你想在图的左侧有线条的比例,你可以在之后交换比例:

import pandas as pd
test = {"index": range(10), 
        "line": [i**2 for i in range(10)], 
        "bar": [100*i*10 for i in range(10)]}
test=pd.DataFrame(test)

ax  = test.plot(x="index",y="bar",color="r",kind="bar")
ax2 = test.plot(x="index",y="line", color="b", ax=ax, secondary_y=True)

ax.yaxis.tick_right()
ax2.yaxis.tick_left()
ax.set_ylabel("bar", color="r")
ax2.set_ylabel("line", color="b")
ax.yaxis.set_label_position("right")
ax2.yaxis.set_label_position("left")

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多