【问题标题】:ValueError: shape mismatch: objects cannot be broadcast to a single shape Python ErrorValueError:形状不匹配:无法将对象广播到单个形状 Python 错误
【发布时间】:2021-05-13 08:11:12
【问题描述】:

代码

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

data = pd.read_csv("../Heart_Disease_Prediction.csv")
boy = data[data.Sex == 1]
girl = data[data.Sex == 0]

plt.figure("Heart Disease", figsize=(8, 5))
plt.title("Cholesterol Levels for Heart Diseases for Age Groups", size=11)
plt.xlabel("Age", size=11)
plt.ylabel("Cholesterol Level", size=11)
plt.axis([28, 80, 0, 400])
plt.grid(color="k", linewidth=0.5, linestyle="dotted")

x_age = np.arange(len(data.Age))
width = 0.25

plt.bar(x_age - width, boy.Cholesterol, color="#444444", label="Boy")
plt.bar(x_age + width, girl.Cholesterol, color="tab:blue", label="Girl")

plt.xticks(ticks=x_age, labels=data.Age)
plt.legend(prop={"size": 10}, loc="upper left")
plt.show()

问题

我正在使用这些代码行,但它一直给我一个“ValueError:形状不匹配:对象不能广播到单个形状”错误。有什么办法解决这个问题?

【问题讨论】:

  • 嗨@heman,如果您提供minimum reproducible example 会更好,因为我们无权访问数据。如果您提供完整的回溯/错误消息,也会有所帮助。该错误可能与x_ageboy.Cholesterol(或girl.Cholesterol)的长度不同有关。

标签: python pandas numpy matplotlib


【解决方案1】:

以下链接一定能帮到你 https://cumsum.wordpress.com/2020/08/30/matplotlib-valueerror-shape-mismatch-objects-cannot-be-broadcast-to-a-single-shape/

原因是在绘图时,您总是希望 x 坐标和 y 坐标成对出现。如果它们的长度不同,matplotlib 无法弄清楚如何绘制它。

因此,当您收到此错误时,请仔细检查您对绘图函数的输入,并确保它们是您想要的。

【讨论】:

    猜你喜欢
    • 2013-06-01
    • 1970-01-01
    • 2021-05-22
    • 2021-02-27
    • 1970-01-01
    • 2019-02-16
    • 2020-04-28
    • 2021-07-17
    相关资源
    最近更新 更多