来自dataframe值的Matplotlib条形图错误:大小不兼容:参数“height”必须是length

2024-09-27 21:25:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用数据框做一个简单的条形图。我的数据框如下所示:

    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

我的代码基本上是这样的:

^{pr2}$

但是我得到了以下错误:

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

Tags: 数据inpyhomematplotliblibpackagesline
1条回答
网友
1楼 · 发布于 2024-09-27 21:25:40

不确定这是不是你想要的。它是根据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

相关问题 更多 >

    热门问题