2017-06-12 5 views
1

棒グラフの棒グラフをどのようにプロットするのですかパンダデータフレームplotを使用する方法はありますか?パンダデータフレームバープロット - プロットバー異なる色の特定のカラーマップ

私はこのデータフレームを使用している場合:

  1. が「ペア」カラーマップ
  2. プロット各バーを使用します:df.plot()引数が、私はそうプロットの各バーを設定する必要が何

    df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index() 
    
        index count 
    0  0 3372 
    1  1 68855 
    2  2 17948 
    3  3 708 
    4  4 9117 
    

    別の色

私が試していること:

df.plot(x='index', y='count', kind='bar', label='index', colormap='Paired', use_index=False) 

結果:

not different colors

私はすでに知っている(はい、これは動作しますが、再び、私の目的はONLY でこれを行う方法を見つけ出すことです何。確かにそれが可能でなければならない):?

def f(df): 
    groups = df.groupby('index') 

    for name,group in groups: 
    plt.bar(name, group['count'], label=name, align='center') 

    plt.legend() 
    plt.show() 

end result but used for loop

答えて

1

あなたは、単一の列ごとに異なるバーを色付けに渡すことができる引数はありません。
異なる列のためのバーが異なって色付けされているので、オプションは、プロットする前にデータフレームを転置することで、

ax = df.T.plot(kind='bar', label='index', colormap='Paired') 

これは、現在のサブグループの一部としてデータを引きます。したがって、制限とxlabelsを正しく設定するには、いくつかの調整が必要です。

import matplotlib.pyplot as plt 
import pandas as pd 

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index() 

ax = df.T.plot(kind='bar', label='index', colormap='Paired') 
ax.set_xlim(0.5, 1.5) 
ax.set_xticks([0.8,0.9,1,1.1,1.2]) 
ax.set_xticklabels(range(len(df))) 
plt.show() 

enter image description here

私はこのソリューションは質問から基準に一致すると思いますが、plt.barを使うことには何も問題は実際にはありません。 plt.barへの単一の呼び出しで十分です

plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df)))) 

enter image description here

完全なコード:

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

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index() 

plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df)))) 

plt.show() 
関連する問題