2016-10-29 15 views
2
Groups Counts 
1 0-9  38 
3 10-19 41 
5 20-29 77 
7 30-39 73 
9 40-49 34 

私は、x軸上のグループとy軸上のCountを持つmatplotlib.pyplotライブラリを使って棒グラフを作成したいと思います。私は、次のコードMatplotlib.pyplotを使ってPythonで棒グラフをプロットする

ax = plt.subplots() 
    rects1 = ax.bar(survived_df["Groups"], survived_df["Counts"], color='r') 
    plt.show() 

を使用してそれを試してみたが、私は取得してい次のエラー

invalid literal for float(): 0-9 
+0

明らかに(エラーメッセージが伝えたように)データ型あなたのグループの列はフロートと互換性がありません。あなたのデータ型は?文字列?どのようなオブジェクトが 'survived_df'なのか。あなたはパンダを使っていますか?それをタグに追加してください! – dnalow

答えて

5

の左辺のX座標に対応した番号でなければならないplt.bar関数に与えられた最初の配列バー。あなたの場合、[0-9, 10-19, ...]は有効な引数として認識されません。

ただし、DataFrameのインデックスを使用して棒グラフを作成し、x-ticks(ラベルをx軸に配置する場所)の位置を定義してから、xティックのラベルをグループ名。

fig,ax = plt.subplots() 
ax.bar(survived_df.index, survived_df.Counts, width=0.8, color='r') 
ax.set_xticks(survived_df.index+0.4) # set the x ticks to be at the middle of each bar since the width of each bar is 0.8 
ax.set_xticklabels(survived_df.Groups) #replace the name of the x ticks with your Groups name 
plt.show() 

enter image description here

あなたも1つのライナーで直接Pandasプロット機能を使用することができます注:

survived_df.plot('Groups', 'Counts', kind='bar', color='r') 

enter image description here

関連する問題