gpt4 book ai didi

Python Pandas 绘制由 secondary_y 更改的图层顺序

转载 作者:太空狗 更新时间:2023-10-30 02:39:48 26 4
gpt4 key购买 nike

我正在尝试将线图和条形图合并为一个图。数据源是 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)

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

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

然后条形图会在线上,这不是我想要的。

这是两个图:

Use only one y axis Use both left and right y axis

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

如有任何建议或帮助,我们将不胜感激。

最佳答案

第二个轴将始终在第一个轴之上。所以你需要最后绘制线图,让它出现在条形图的顶部。您可以考虑以下解决方案,将线设置为二级刻度:

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")

enter image description here

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

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")

enter image description here

关于Python Pandas 绘制由 secondary_y 更改的图层顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43397810/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com