python - Matplotlib 条形图错误 - TypeError : only size-1 arrays can be converted to Python scalars

标签 python matplotlib

假设我有以下 DataFrame:

import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime as dt

df = pd.DataFrame(
    [
        ['2008-02-19', 10],
        ['2008-03-01', 15],
        ['2009-02-05', 20],
        ['2009-05-10', 40],
        ['2010-10-10', 25],
        ['2010-11-15', 5]
    ],
    columns = ['Date', 'DollarTotal']
)
df

df

我想绘制按年份求和的总和,因此我执行以下转换:

df['Date'] = pd.to_datetime(df['Date'])
df_Year = df.groupby(df['Date'].dt.year)
df_Year = df_Year.sum('DollarTotal')
df_Year

df_Year

matplotlib 中的以下代码创建了下面的图表:

fig,ax = plt.subplots()
ax.plot(df_Year.index, df_Year.values)
ax.set_xlabel("OrderYear")
ax.set_ylabel("$ Total")
ax.set_title("Annual Purchase Amount")
plt.xticks([x for x in df_Year.index], rotation=0)
plt.show()

plot

当我想使用相同的 DataFrame 创建一个条形图 时,就会出现问题。通过将上面的代码从 ax.plot 更改为 ax.bar,我得到以下错误:

error

我以前在 matplotlib 中绘图时从未遇到过这个错误。我做错了什么?

请参阅以下 dm2 解决此问题的答案。


编辑:

我刚刚弄明白为什么我过去从来没有遇到过这个问题。这与我如何对 groupby 求和有关。如果我将 df_Year = df_Year.sum('DollarTotal') 替换为 df_Year = df_Year['DollarTotal'].sum() 那么这个问题就不会发生。

df = pd.DataFrame(
    [
        ['2008-02-19', 10],
        ['2008-03-01', 15],
        ['2009-02-05', 20],
        ['2009-05-10', 40],
        ['2010-10-10', 25],
        ['2010-11-15', 5]
    ],
    columns = ['Date', 'DollarTotal']
)
df['Date'] = pd.to_datetime(df['Date'])
df_Year = df.groupby(df['Date'].dt.year)
df_Year = df_Year['DollarTotal'].sum()
df_Year

df_sum

fig,ax = plt.subplots()
ax.bar(df_Year.index, df_Year.values)
ax.set_xlabel("OrderYear")
ax.set_ylabel("$ Total")
ax.set_title("Annual Purchase Amount")
plt.xticks([x for x in df_Year.index], rotation=0)
plt.show()

enter image description here

最佳答案

来自 matplotlib.axes.Axes.bar documentation ,该函数期望高度参数是标量或标量序列。 pandas.DataFrame.values 是一个二维数组,第一维是行,第二维是列(即使只有一列,它也是一个二维数组),所以它是一个序列阵列。因此,如果您使用 df.values,您还需要将其整形为标量的预期序列(即一维数组)(即 df.values.reshape(len(df) )).

或者,特别是在您的代码中:ax.bar(df_Year.index, df_Year.values.reshape(len(df_Year))

结果:

enter image description here

关于python - Matplotlib 条形图错误 - TypeError : only size-1 arrays can be converted to Python scalars,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66154591/

相关文章:

python - 如何编写一个用 @defer.inlineCallbacks 装饰的方法,该方法可能会产生也可能不会产生?

python - 金贾 : loop to create form fields with same name but the last character

python - 在电报机器人中,/未按编码弹出/大写

python - 设置 DEBUG 环境变量时,如何禁用 numba 调试日志记录?

python - plt.subplots() 中的轴是一个 "numpy.ndarray"对象并且没有属性 "plot"

python - 在循环中创建的 Matplotlib 子图不显示数据

python - 如何在 Python 中随时间改变动态系统的参数?

python - 在 matplotlib 动画模块中管理动态绘图

python - 'pick_event' 处理程序未拾取 Matplotlib 行

python - Matplotlib 绘图 : AttributeError: 'list' object has no attribute 'xaxis'