【问题标题】:Matplotlib bar chart from dataframe ValueError: incompatible sizes: argument 'height' must be length来自数据框 ValueError 的 Matplotlib 条形图:大小不兼容:参数“高度”必须是长度
【发布时间】:2017-06-26 11:27:02
【问题描述】:

我正在尝试从数据框中制作一个简单的条形图。我的数据框如下所示:

    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

【问题讨论】:

  • 基本上,错误消息显示您的height(即y)与您的left(即x)不匹配。你的 left 似乎有 6101 个元素,而你的 height 没有正好 6101 个元素。此外,您的示例代码似乎很奇怪。您的 x 已转换为 str。那么你的 ax.bar() 应该会失败,因为 left 假设是“标量序列”。
  • 谢谢。这对我来说确实很有意义,因为数据框有 338 行。我将 x 转换为 str 因为我不希望 x 值按日期排序。我想将它们视为字符串(数据框按 y 值排序)。您对如何使用 matplotlib 将数据框绘制为条形图有什么建议吗?
  • 您可以尝试修改example,看看是否可以满足您的需求。我在下面举一个例子。但老实说,我不知道这是否是你想要的。

标签: python matplotlib bar-chart


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-23
    • 2018-01-28
    • 2018-11-04
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    相关资源
    最近更新 更多