【问题标题】:Arrange two plots horizontally水平排列两个图
【发布时间】:2016-08-22 03:36:09
【问题描述】:

作为练习,我正在使用 matplotlib 复制 The Economist 中的一个情节

到目前为止,我可以生成一个随机数据并独立生成两个图。我现在正在努力将它们水平地放在一起。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

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'))
df1.plot.bar(stacked=True)

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

plt.figure()
fig, ax1 = plt.subplots()
ax1.plot(df2['avg_hour'])

ax2 = ax1.twinx()
ax2.bar(left=range(2009,2016),height=df2['usage'])

plt.show()

【问题讨论】:

    标签: pandas matplotlib


    【解决方案1】:

    您应该尝试使用子图。首先,您通过plt.figure() 创建一个图形。然后添加一个subplot(121),其中 1 是行数,2 是列数,最后 1 是您的第一个绘图。然后绘制第一个数据框,注意您应该使用创建的轴ax1。然后添加第二个subplot(122) 并重复第二个数据帧。我将您的轴 ax2 更改为 ax3,因为现在您在一个图形上有三个轴。下面的代码产生了我相信你正在寻找的东西。然后,您可以分别处理每个情节的美学。

    %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()
    

    【讨论】:

    • 更新到这个,应该是ax3.bar(range(2009,2016), height=df2['usage'])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 2014-01-29
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多