Python Pandas plots layer order changed by secondary_y

后端 未结 1 1797
夕颜
夕颜 2021-01-18 18:15

I\'m trying to merge a line plot and a bar plot into one plot. The data source is a pandas dataframe.

Here is a demo:

import pandas as pd
test = {\"i         


        
相关标签:
1条回答
  • 2021-01-18 18:37

    The second axes will always be on top of the first. So you need to plot the line plot last to have it appear on top of the bars. You may consider the following solution, which sets the line to the secondary scale:

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

    If you then want to have the scale for line on the left side of the plot, you can exchange the scales afterwards:

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

    0 讨论(0)
提交回复
热议问题