水平排列两个图

时间:2016-08-22 03:36:10

标签: pandas matplotlib

作为练习,我正在使用matplotlib enter image description here

复制经济学人的情节。

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

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

1 个答案:

答案 0 :(得分:2)

您应该尝试使用子图。首先,您按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()

enter image description here

相关问题