【问题标题】:ValueError: shape mismatch: objects cannot be broadcast to a single shape When Trying to Offset BarsValueError:形状不匹配:尝试偏移条时无法将对象广播到单个形状
【发布时间】:2021-07-17 03:57:27
【问题描述】:

我正在尝试在双条形图上绘制 _lst_onelst_two,其中 y 轴是 ACT 和 SAT 的分数(范围为 0-1),x 轴是按以下方式分组的分数4 个值(该州是否要求 SAT、ACT、选择或没有考试要求)。

列表和 x_values 的形状是正确的,当我尝试输入 x 以偏移条形时出现错误。

fig, ax = plt.subplots()

labels = ['ACT', 'No Test', 'SAT', 'ACT or SAT']

lst_one = list(states_2018['sat_percent_total'].values)
lst_two =  list(states_2018['act_percent_total'].values)
x_values = list(states_2018['test_required'].values)

x = np.arange(len(labels))  # the label locations
width = .3  # the width of the bars

ax.bar(x - width/2, x_values, lst_one, width, color ='green')
ax.bar(x + width/2, x_values, lst_two, width, color ='blue')
ax.set_xticklabels(labels);

【问题讨论】:

  • 嗨,Megan,你的哪一行代码抛出了错误?您能否编辑您的问题以包含完整的错误回溯?
  • ax.bar 有一个多余的参数。从给定的代码和丢失的数据中,很难猜测标签与数据帧的对应关系。也许预期的代码是x = np.arange(len(x_values )),然后是ax.bar(x - width/2, lst_one, width, color ='green'),最后是ax.set_xticklabels(x_values )

标签: python pandas matplotlib bar-chart


【解决方案1】:

不清楚您的数据框的格式。我合成了一个。

  • bar xheight 列表的大小必须相同。如果您从数据框中的两列中获取数据,就会出现这种情况
  • 已取消生成不需要的中间列表
fig, ax = plt.subplots()

labels = ['ACT', 'No Test', 'SAT', 'ACT or SAT']

states_2018 = pd.DataFrame({'sat_percent_total':np.random.randint(1,100,10),
                           'act_percent_total':np.random.randint(1,100,10),
                           'test_required':np.random.choice(list("ABCD"), 10)})

width = .3  # the width of the bars

ax.bar(states_2018['test_required'], states_2018['sat_percent_total'], width=width, align="edge", color="green")
ax.bar(states_2018['test_required'], states_2018['act_percent_total'], width=-width, align="edge", color="blue")

ax.set_xticklabels(labels);

【讨论】:

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