numpy - Python matplotlib 畫直方圖出錯?
問題描述
sql3 = ’select sum(comment_num) as total_col,create_time from article GROUP BY create_time’df = pd.read_sql(sql3, conn)print(df)# 總數(shù)# N = 22# 寬度width = 0.45# ind = np.arange(N)plt.bar(df[’create_time’], df[’total_col’], width, color=’r’, label=’total_col’)plt.xlabel(u'發(fā)表日期')plt.ylabel(u'總評論數(shù)')plt.title(u'每日發(fā)表文章的總評論數(shù)直方分布圖')plt.legend()plt.show()
df:
total_col create_time0 2.0 2017-04-271 0.0 2017-05-092 3.0 2017-05-103 6.0 2017-05-114 3.0 2017-05-125 2.0 2017-05-136 1.0 2017-05-147 0.0 2017-05-158 5.0 2017-05-169 0.0 2017-05-17101.0 2017-05-18110.0 2017-05-19126.0 2017-05-22130.0 2017-05-24141.0 2017-05-25150.0 2017-05-26166.0 2017-05-27174.0 2017-05-2918 16.0 2017-05-31194.0 2017-06-02202.0 2017-06-04211.0 2017-06-05
錯誤:
Traceback (most recent call last): File 'D:/PyCharm/py_scrapyjobbole/data_analysis.py', line 46, in <module> plt.bar(df[’create_time’], df[’total_col’], width, color=’r’, label=’total_col’) File 'D:python-3.5.2libsite-packagesmatplotlibpyplot.py', line 2704, in bar **kwargs) File 'D:python-3.5.2libsite-packagesmatplotlib__init__.py', line 1898, in inner return func(ax, *args, **kwargs) File 'D:python-3.5.2libsite-packagesmatplotlibaxes_axes.py', line 2105, in bar left = [left[i] - width[i] / 2. for i in xrange(len(left))] File 'D:python-3.5.2libsite-packagesmatplotlibaxes_axes.py', line 2105, in <listcomp> left = [left[i] - width[i] / 2. for i in xrange(len(left))]TypeError: unsupported operand type(s) for -: ’datetime.date’ and ’float’
問題解答
回答1:試試astype()轉換型別,參見stackoverflow
%matplotlib inlineimport pandas as pddf = pd.DataFrame.from_csv(’timeseries.tsv’, sep='t')df[’total_col’] = df[’total_col’].astype(float)df[’create_time’] = df[’create_time’].astype(’datetime64[D]’)df.set_index([’create_time’]).plot(kind=’bar’)
plt.bar(df[’create_time’], df[’total_col’], width, color=’r’, label=’total_col’)
里面的left, height參數(shù)應該是數(shù)值形的list,你現(xiàn)在df[’create_time’]傳遞的是時間類型的列表
相關文章:
1. android - weex 項目createInstanceReferenceError: Vue is not defined2. javascript - 如圖,百度首頁,查看源代碼為什么什么都沒有?3. 網(wǎng)頁爬蟲 - python requests爬蟲,如何post payload4. npm鏡像站全新上線5. angular.js - 求問大神?angularjs加載外部的html模板。有閃動如何解決6. html - 關于CSS實現(xiàn)border的0.5px設置?7. PHPExcel表格導入數(shù)據(jù)庫怎么導入8. android - 哪位大神知道java后臺的api接口的對象傳到前端后輸入日期報錯,是什么情況?求大神指點9. pdo 寫入到數(shù)據(jù)庫的內容為中文的時候寫入亂碼10. PHP類封裝的插入數(shù)據(jù),總是插入不成功,返回false;
