2017-01-16 6 views
2

私はいくつかのデータを生成し、それらを同じプロット内の2つのグラフとして視覚化しようとしました。 1つはバー、もう1つはラインです。同じデータのMatplotlibグラフは重複しません

ただし、何らかの理由でグラフが重なっていないようです。

は、ここに私のコードです:

# roll two 6-sided dices 500 times 
dice_1 = pd.Series(np.random.randint(1, 7, 500)) 
dice_2 = pd.Series(np.random.randint(1, 7, 500)) 

dices = dice_1 + dice_2 

# plotting the requency of a 2 times 6 sided dice role 
fc = collections.Counter(dices) 
freq = pd.Series(fc) 
freq.plot(kind='line', alpha=0.6, linestyle='-', marker='o') 
freq.plot(kind='bar', color='k', alpha=0.6) 

そしてここグラフです。

enter image description here

データセットは右に同じしかし線グラフが移動される2つのデータポイント(4の代わりに2から始まります)。別にプロットすると、正しく表示されます(両方とも2で始まります)。だから私は同じグラフにそれらをプロットすれば何が違うのですか?そしてこれを修正する方法は?

+0

問題は、私が思うに、ジョーキングトンの答え[ここ]の編集で説明されている(http://stackoverflow.com/questions/7733693/matplotlib-overlay-plot sと異なるスケール)。しかし、それは5歳になりました。これが望ましい行動ではないかと疑っていますので、素晴らしい修正があるかどうか疑問です。まだ見ている。 – roganjosh

答えて

1

x軸データを再供給するよりも簡単な方法を見つけることができませんでした。これがはるかに大きなアプローチの代表であれば、リストを使うのではなくpd.Series()からこのデータをプロットする必要がありますが、このコードは少なくともあなたが望むプロットを提供します。 Python 3を使用している場合は、iteritems()items()に変更してください。

x軸の自動スケーリングは、可能な値)。両方のプロットが作成されるまでx軸上でこの自動縮尺を無効にすることは可能かもしれませんが、これはもっと難しいようです。

import collections 
import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 

# roll two 6-sided dices 500 times 
dice_1 = pd.Series(np.random.randint(1, 7, 500)) 
dice_2 = pd.Series(np.random.randint(1, 7, 500)) 

dices = dice_1 + dice_2 

# plotting the requency of a 2 times 6 sided dice role 
fc = collections.Counter(dices) 

x_axis = [key for key, value in fc.iteritems()] 
y_axis = [value for key, value in fc.iteritems()] 

plt.plot(x_axis, y_axis, alpha=0.6, linestyle='-', marker='o') 
plt.bar(x_axis, y_axis, color='k', alpha=0.6, align='center') 
plt.show() 
1

設定系列プロットの使用インデックスは、use_index問題を修正しますFalseに、私はまた、それぞれの組み合わせの頻度をカウントするgroupbylenを使用することをお勧め

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

# roll two 6-sided dices 500 times 
dice_1 = pd.Series(np.random.randint(1, 7, 500)) 
dice_2 = pd.Series(np.random.randint(1, 7, 500)) 
dices = dice_1 + dice_2 

# returns the corresponding value of each index from dices 
func = lambda x: dices.loc[x] 

fc = dices.groupby(func).agg({'count': len}) 

ax = fc.plot(kind='line', alpha=0.6, linestyle='-', 
      marker='o', use_index=False) 
fc.plot(ax=ax, kind='bar', alpha=0.6, color='k') 

plt.show() 

結果が示されているためです下の plot

関連する問題