水平排列两个地块

kng*_*yen 1 matplotlib pandas

作为练习,我正在用 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()
Run Code Online (Sandbox Code Playgroud)

omd*_*mdv 6

您应该尝试使用子图。首先,您通过plt.figure(). 然后添加一个subplot(121),其中 1 是行数,2 是列数,最后 1 是您的第一个图。然后绘制第一个数据框,注意您应该使用创建的 axis 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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明