Legend only shows one label when plotting with pandas

前端 未结 3 1386
青春惊慌失措
青春惊慌失措 2020-11-30 03:54

I have two Pandas DataFrames that I\'m hoping to plot in single figure. I\'m using IPython notebook.

I would like the legend to show the label for both of the DataFr

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 04:50

    You can use pd.concat to merge the two dataframes and then plot is using a secondary y-axis:

    import numpy as np  # For generating random data.
    import pandas as pd
    
    # Creating data.
    np.random.seed(0)
    prng = pd.period_range('1/1/2011', '1/1/2012', freq='M')
    var = pd.DataFrame(np.random.randn(len(prng)), index=prng, columns=['total'])
    shares = pd.DataFrame(np.random.randn(len(prng)), index=prng, columns=['average'])
    
    # Plotting.
    ax = (
        pd.concat([var, shares], axis=1)
        .rename(columns={
            'total': 'Variance of Low Wages',
            'average': 'Average Age'
        })
        .plot(
            title='Wage Variance and Mean Age',
            secondary_y='Average Age')
    )
    ax.set_ylabel('Variance of Low Wages')
    ax.right_ax.set_ylabel('Average Age', rotation=-90)
    

提交回复
热议问题