2016-08-22 79 views
0

作为练习两个地块,我再现来自经济学人的阴谋与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

你应该尝试使用子图。首先你创建一个数字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