Arrange two plots horizontally

前端 未结 1 1533
终归单人心
终归单人心 2021-01-26 18:23

As an exercise, I\'m reproducing a plot from The Economist with matplotlib

So far, I can generate a random data and produce two plots independently. I\'m struggling now

1条回答
  •  醉梦人生
    2021-01-26 19:08

    You should try using subplots. First you create a figure by plt.figure(). Then add one subplot(121) where 1 is number of rows, 2 is number of columns and last 1 is your first plot. Then you plot the first dataframe, note that you should use the created axis ax1. Then add the second subplot(122) and repeat for the second dataframe. I changed your axis ax2 to ax3 since now you have three axis on one figure. The code below produces what I believe you are looking for. You can then work on aesthetics of each plot separately.

    %matplotlib inline
    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure()
    df1 = pd.DataFrame({"broadcast": np.random.randint(110, 150,size=8), 
                       "cable": np.random.randint(100, 250, size=8),
                       "streaming" : np.random.randint(10, 50, size=8)}, 
                       index=pd.Series(np.arange(2009,2017),name='year'))
    ax1 = fig.add_subplot(121)
    df1.plot.bar(stacked=True,ax=ax1)
    
    df2 = pd.DataFrame({'usage': np.sort(np.random.randint(1,50,size=7)), 
                        'avg_hour': np.sort(np.random.randint(0,3, size=7) + np.random.ranf(size=7))},
                          index=pd.Series(np.arange(2009,2016),name='year'))
    
    ax2 = fig.add_subplot(122)
    ax2.plot(df2['avg_hour'])
    
    ax3 = ax2.twinx()
    ax3.bar(left=range(2009,2016),height=df2['usage'])
    
    plt.show()
    

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