我试图从数据框中制作一个简单的条形图。我的数据框如下所示:
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
答案 0 :(得分: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()