2016-08-22 6 views
0

を配置し、私はこれまでのところ、私は、ランダムなデータを生成することができますし、独立して二つのグラフを生成matplotlibのenter image description hereは練習として水平に2つのプロット

とエコノミストからプロットを再現しています。私は今、彼らを横にお互いに置くことで苦労しています。

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()で図を作成します。次に、1を追加します。subplot(121) 1は行数、2は列数、最後は1が最初のプロットです。次に、最初のデータフレームをプロットします。作成された軸ax1を使用する必要があることに注意してください。その後、2番目のデータフレームに2番目のsubplot(122)を追加して繰り返します。あなたの軸ax2ax3に変更しました。以下のコードは、私があなたが探していると信じているものを生成します。その後、各プロットの美しさを個別に操作できます。

%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

関連する問題