2016-11-15 53 views
0

我有一個數據幀如下plt.errorbar的X字符串值

import pandas as pd 
import matplotlib.pylab as plt 
df = pd.DataFrame({'name':['one', 'two', 'three'], 'assess':[100,200,300]}) 

我想建立errorbar這樣

c = 30 
plt.errorbar(df['name'], df['assess'], yerr=c, fmt='o') 

,當然我得到

ValueError: could not convert string to float 

我可以將字符串轉換爲浮點數,但是我正在丟失值簽名,也許有一種更優雅的方式?

+0

可能dublicate http://stackoverflow.com/questions/40266187/matplotlib-cannot-plot-categorical-values或http://stackoverflow.com/questions/40510070/plotting-in-python3-histogram或http://stackoverflow.com/questions/31029560/plotting-categorical-data-with-pandas-and-matplotlib或http://stackoverflow.com/questions/32294586/categorical-data-in-subplots或http://stackoverflow.com/questions/33958068/matplotlib-how-to-plot-a-line-with-categorical-data-on-the-x-axis – ImportanceOfBeingErnest

回答

2

Matplotlib確實只能使用數值數據。有一個example in the matplotlib collection顯示如何處理您有分類數據的情況。解決方案是繪製一系列值,然後使用plt.xticks(ticks, labels)ax.set_xticks(ticks)ax.set_xticklabels(labels)的組合來設置標籤。

在你的情況下,前者的作品罰款:的

import pandas as pd 
import matplotlib.pylab as plt 
df = pd.DataFrame({'name':['one', 'two', 'three'], 'assess':[100,200,300]}) 

c = 30 
plt.errorbar(range(len(df['name'])), df['assess'], yerr=c, fmt='o') 
plt.xticks(range(len(df['name'])), df['name']) 

plt.show() 
+0

thanx!我試圖使用df.index,但在蜱中出現錯誤 – Edward