secondary_y=True changes x axis in pandas

前端 未结 2 1460
心在旅途
心在旅途 2020-12-20 04:44

I\'m trying to plot two series together in Pandas, from different dataframes.

Both their axis are datetime objects, so they can be plotted together:



        
相关标签:
2条回答
  • 2020-12-20 04:49
    import matplotlib.pyplot as plt
    import pandas as pd
    from numpy.random import random
    
    df = pd.DataFrame(random((15,2)),columns=['a','b'])
    df.a = df.a*100
    
    fig, ax1 = plt.subplots(1,1)
    df.a.plot(ax=ax1, color='blue', label='a')
    ax2 = ax1.twinx()
    df.b.plot(ax=ax2, color='green', label='b')
    ax1.set_ylabel('a')
    ax2.set_ylabel('b')
    ax1.legend(loc=3)
    ax2.legend(loc=0)
    plt.show()
    

    enter image description here

    0 讨论(0)
  • 2020-12-20 04:53

    I had the same issue, always getting a strange plot when I wanted a secondary_y.

    I don't know why no-one mentioned this method in this post, but here's how I got it to work, using the same example as cphlewis:

    import matplotlib.pyplot as plt
    import pandas as pd
    from numpy.random import random
    
    df = pd.DataFrame(random((15,2)),columns=['a','b'])
    ax = df.plot(secondary_y=['b'])
    plt.show()
    

    Here's what it'll look like

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