2017-06-26 17 views
0

我想從數據框中製作一個簡單的條形圖。我的數據幀是這樣的:來自數據幀的Matplotlib條形圖ValueError:不兼容的大小:參數'height'必須是長度

start_date  AvgPrice 
0 2018-03-17 3146.278673 
1 2018-12-08 3146.625048 
2 2018-11-10 3148.762809 
3 2018-11-17 3151.926036 
4 2018-11-03 3153.965413 
5 2018-02-03 3155.831255 
6 2018-11-24 3161.057180 
7 2018-01-27 3162.143680 
8 2018-03-10 3162.239096 
9 2018-01-20 3166.450869 
..   ...   ... 
337 2018-07-13 8786.797679 
338 2018-07-20 8969.859386 

我的代碼基本上是這樣的:

x = df.start_date 
x = x.to_string() #convert datetime objects to strings 
y = df.AvgPrice 

# Plot data 
fig, ax = plt.subplots() 

ax.bar(x, y, width=30) 

fig.savefig('week price bar chart') 

plt.close(fig) 

不過,我得到以下錯誤:

File "PriceHistogram.py", line 68, in plot 
ax.bar(x, y, width=30) 
File "/home/rune/env3/lib/python3.6/site-packages/matplotlib/__init__.py", line 1898, in inner 
    return func(ax, *args, **kwargs) 
File "/home/rune/env3/lib/python3.6/site-packages/matplotlib/axes/_axes.py", line 2079, in bar 
    "must be length %d or scalar" % nbars) 
ValueError: incompatible sizes: argument 'height' must be length 6101 or scalar 
+1

基本上,錯誤消息說你的'height'(這是'y')不符合您的'left'(這是'x')。你的'left'似乎有6101個元素,而你的'height'完全沒有6101個元素。此外,你的示例代碼看起來很奇怪。你的'x'被轉換爲'str'。那麼你的'ax.bar()'應該失敗,因爲'left'應該是「標量序列」。 –

+0

謝謝。這對我來說確實很有意義,儘管數據框有338行。我將x轉換爲str,因爲我不想按日期排序x值。我想將它們視爲字符串(數據框由y值排序)。你有關於如何將數據框圖繪製爲matplotlib的條形圖的建議? – Wessi

+1

你可以嘗試修改[示例](https://matplotlib.org/examples/api/barchart_demo.html),看看它是否能給你你想要的。我在下面舉一個例子。但說實話,我不知道這是否是你想要的。 –

回答

1

不能確定,如果這是你想。它是從matplotlib的文檔中的example修改而來的。

import io 

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

s = """start_date AvgPrice 
2018-03-17 3146.278673 
2018-12-08 3146.625048 
2018-11-10 3148.762809 
2018-11-17 3151.926036 
2018-11-03 3153.965413 
2018-02-03 3155.831255 
2018-11-24 3161.057180 
2018-01-27 3162.143680 
2018-03-10 3162.239096 
2018-01-20 3166.450869""" 

df = pd.read_table(io.StringIO(s), sep=' ', header=0) 

fig, ax = plt.subplots() 
width = 0.8 
b = ax.bar(np.arange(len(df.AvgPrice)), df.AvgPrice, width=width) 
ax.set_xticks(np.arange(len(df.AvgPrice)) + width/2) 
ax.set_xticklabels(df.start_date, rotation=90) 
plt.show() 

enter image description here

相關問題