Python Pandas reorders layers to second_y

I am trying to combine a linear plot and a bar into one plot. The data source is the pandas framework.

Here is a demo:

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)

Everything is good so far, you can see that the line is above the bars. If I ask the barrel to use the secondary yaxis on the right, changing the last line as follows:

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

Then the bars will be on top of the line that does not match me.

Here are two graphs:

Use only one y axis Use left and right y axis

I tried to build the bar first and then build the line, and I also tried to use zorderto force the line over the panel, but none of them work.

Any suggestions or help would be appreciated.

+4
source share
1 answer

. , . , :

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

+3

Source: https://habr.com/ru/post/1674769/


All Articles