无法使用ndarray的pyplot绘制双条条形图

2024-04-28 16:42:01 发布

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

我得到了2{ndarray},它有3个值:正、负和中性。

>>>y1
array([82, 80, 63])
>>>y2
array([122,  73,  30])

同样,我需要将y1[0]y2[0]绘制在一起,因为它们对应为正值,每个数组中的其他2个值也是如此。

我试过这个:

import matplotlib.pyplot as plt
import numpy as np

def biplt(groundTruth, predictedValues, plt_name='<name>'):
        gt = groundTruth
        pr = predictedValues
        x = np.arange(2)

        y1, y2 = gt.values, pr.values
        fig, axes = plt.subplots(ncols=1, nrows=1)

        width = 0.20
        plt.title('%s\n Accuracy Score' % plt_name)
        plt.xlabel('Parameters')
        plt.ylabel('Score')
        axes.bar(x, y1, width, label="Algorithm 1")
        axes.bar(x + width, y2, width, color=list(plt.rcParams['axes.prop_cycle'])[2]['color'], label="Algorithm 2")
        axes.set_xticks(x + width)
        axes.set_xticklabels(['Positive', 'Negative'])
        plt.legend()
        plt.show()

导致ValueError,请检查以下内容:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

我无法诊断可能的形状有问题

我希望有一个类似的o/p:
2Bars for each criteria


Tags: nameimportgtasnppltprwidth
2条回答

np.arange(2)给出array([0, 1]),因此只有两个值。如果您尝试对此绘制三个值(在y1y2),则这将不起作用,并将抛出ValueError(确切地告诉您这一点):

ValueError: shape mismatch: objects cannot be broadcast to a single shape

尝试使用np.arange(3)

例外情况是,您试图将3y值与2个x值进行比较(请参见documentation on ^{})。

下面是生成所需输出的修改代码:

y1 = np.array([82, 80, 63])
y2 = np.array([122,  73,  30])

x = np.arange(len(y1))
width = 0.20

fig, axes = plt.subplots(ncols=1, nrows=1)
plt.title('Accuracy Score')
plt.xlabel('Parameters')
plt.ylabel('Score')
axes.bar(x, y1, width=-1.*width, align='edge', label="Algorithm 1")
axes.bar(x, y2, width=width, align='edge', color=list(plt.rcParams['axes.prop_cycle'])[2]['color'], label="Algorithm 2")
axes.set_xticks(x)
axes.set_xticklabels(['Positive', 'Negative', 'Neutral'])
plt.legend()
plt.show()

enter image description here

相关问题 更多 >