Python Pandas绘制图层顺序更改为secondary_y

Too*_*ung 4 python matplotlib 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)
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很好,您可以看到线条在条形上方。如果我通过将最后一行更改为以下内容来使用右侧的次要yaxis询问小节图:

test.plot(x="index",y="bar",color="r",kind="bar",ax=ax, secondary_y=True)
Run Code Online (Sandbox Code Playgroud)

然后,这些条将位于该行的顶部,这不是我想要的。

这是两个图:

仅使用一个y轴 同时使用左右y轴

我尝试先绘制条形图,然后再绘制线,我也尝试使用zorder将线强制在条形图上方,但是它们都不起作用。

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

Imp*_*est 5

第二个轴将始终位于第一个轴的顶部。因此,您需要最后绘制线图以使其显示在条形图的顶部。您可以考虑以下解决方案,该解决方案将线设置为次级刻度:

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")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

然后,如果要在图的左侧显示直线比例尺,则可以在以后交换比例尺:

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")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明