2016-08-26 7 views
2

私は、Matplotlibを使用してDataFrameのデータの棒グラフをプロットしています。私は、データセット全体の上に最初のプロットにこの構成を使用します。私は、データの特定のサブセット上でそうしたい除いMatplotlibを使用してデータのサブセットをプロットする

import pandas as pd 
from collections import Counter 
import matplotlib.pyplot as plt 

Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CONS']) 
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index').sort_index() 
df.plot(kind = 'bar', title = '1969-2015 National Temp Bins', legend = False, color = ['r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b','r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g' ]) 

今私は、データの同じ列をプロットしたいと思います。 'region_name'の各領域について、棒グラフを生成したいと思います。ここに私のDataFrameの例があります。

enter image description here

私の未遂ソリューションは、書くことです:

if weatherDFConcat['REGION_NAME'].any() == 'South': 
    Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CONS']) 
    df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index').sort_index() 
    df.plot(kind = 'bar', title = '1969-2015 National Temp Bins', legend = False, color = ['r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b','r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g' ]) 
    plt.show() 

私はこのコードを実行すると、それは奇妙なだけ「南」領域のために動作します。 'South'ではプロットが生成されますが、その他の地域ではコードが実行されます(エラーメッセージは表示されません)が、プロットは表示されません。 south以外の地域でコードを実行すると、コンソールにこの結果が表示されます。

enter image description here

南領域が他の領域は、さらに、ダウンしていると40万行の長さで私のデータフレームの最初の部分です。私がプロットしようとしているDataFrameのサイズは、これと何か関係がありますか?私が正しくあなたの質問を理解していた場合

+0

あなたがいることを使用して別のデータフレームに領域を抽出だけしてみてくださいました他の名前との比較式ですか?それは動作しますか? – wwii

答えて

1

、あなたは前プロットに二つのことをやろうとしている:REGION_NAMEに基づいて

  1. フィルター。

  2. フィルタリングされたデータフレーム内で、TEMPBIN_CONS列の各値が何回表示されます。

あなたは右のパンダの中にそれらのものの両方を行うことができます。

import pandas as pd 
import matplotlib.pyplot as plt 

df = pd.DataFrame({'STATE_NAME': ['Alabama', 'Florida', 'Maine', 'Delaware', 'New Jersey'], 
         'GEOID': [1, 2, 3, 4, 5], 
       'TEMPBIN_CONS': ['-3 to 0', '-3 to 0', '0 to 3', '-3 to 0', '0 to 3'], 
        'REGION_NAME': ['South', 'South', 'Northeast', 'Northeast', 'Northeast']}, 
         columns=['STATE_NAME', 'GEOID', 'TEMPBIN_CONS', 'REGION_NAME']) 

df_northeast = df[df['REGION_NAME'] == 'Northeast'] 
northeast_count = df_northeast.groupby('TEMPBIN_CONS').size() 

print df 
print df_northeast 
print northeast_count 

northeast_count.plot(kind='bar') 
plt.show() 

出力:

STATE_NAME GEOID TEMPBIN_CONS REGION_NAME 
0  Alabama  1  -3 to 0  South 
1  Florida  2  -3 to 0  South 
2  Maine  3  0 to 3 Northeast 
3 Delaware  4  -3 to 0 Northeast 
4 New Jersey  5  0 to 3 Northeast 

    STATE_NAME GEOID TEMPBIN_CONS REGION_NAME 
2  Maine  3  0 to 3 Northeast 
3 Delaware  4  -3 to 0 Northeast 
4 New Jersey  5  0 to 3 Northeast 

TEMPBIN_CONS 
-3 to 0 1 
0 to 3  2 
dtype: int64 

enter image description here

+0

ありがとう - 簡単なソリューションと完璧に動作します。私はプログラミングを始めたばかりであり、とても感謝しています。 – Justin

関連する問題