Python Matplotlib在一个图形中绘制多个条形图

Python Matplotlib在一个图形中绘制多个条形图,python,matplotlib,Python,Matplotlib,我有一个带有多个不同场景的条形图,但当我绘制它时,所有的条形图都会重复。请在下面找到我的代码 我知道我一次只使用列表中的一个值,但是当我尝试使用data[0]传递整个子数组时,我得到一个值不匹配错误: ValueError:形状不匹配:无法将对象广播到单个形状 我做错了什么?我查看了和post,并将一个数组传递给ax.bar import numpy as np import pandas as pd import matplotlib.pyplot as plt data = [[20, 3

我有一个带有多个不同场景的条形图,但当我绘制它时,所有的条形图都会重复。请在下面找到我的代码

我知道我一次只使用列表中的一个值,但是当我尝试使用
data[0]
传递整个子数组时,我得到一个值不匹配错误:

ValueError:形状不匹配:无法将对象广播到单个形状

我做错了什么?我查看了和post,并将一个数组传递给
ax.bar

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

data = [[20, 35, 30, 40], [25, 40, 45, 30], 
        [15, 20, 35, 45], [10, 25, 40, 15], 
        [50, 20, 45, 55], [10, 55, 60, 20]]
data_std = [[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], 
            [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]]    

length = len(data)
x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

# Set plot parameters
fig, ax = plt.subplots()
width = 0.2 # width of bar
x = np.arange(length)

ax.bar(x, data[0][0], width, color='#000080', label='Case-1', yerr=data_std[0][0])
ax.bar(x + width, data[0][1], width, color='#0F52BA', label='Case-2', yerr=data_std[0][1])
ax.bar(x + (2 * width), data[0][2], width, color='#6593F5', label='Case-3', yerr=data_std[0][2])
ax.bar(x + (3 * width), data[0][3], width, color='#73C2FB', label='Case-4', yerr=data_std[0][3])

ax.set_ylabel('Metric')
ax.set_ylim(0,75)
ax.set_xticks(x + width + width/2)
ax.set_xticklabels(x_labels)
ax.set_xlabel('Scenario')
ax.set_title('Title')
ax.legend()
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

fig.tight_layout()
plt.show()
结果是:


您希望按列绘制数据。因此,将列表转换为数组并选择要打印的相应列是有意义的

import numpy as np
import matplotlib.pyplot as plt

data = np.array([[20, 35, 30, 40], [25, 40, 45, 30], 
                 [15, 20, 35, 45], [10, 25, 40, 15], 
                 [50, 20, 45, 55], [10, 55, 60, 20]])
data_std = np.array([[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], 
                     [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]])    

length = len(data)
x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

# Set plot parameters
fig, ax = plt.subplots()
width = 0.2 # width of bar
x = np.arange(length)

ax.bar(x, data[:,0], width, color='#000080', label='Case-1', yerr=data_std[:,0])
ax.bar(x + width, data[:,1], width, color='#0F52BA', label='Case-2', yerr=data_std[:,1])
ax.bar(x + (2 * width), data[:,2], width, color='#6593F5', label='Case-3', yerr=data_std[:,2])
ax.bar(x + (3 * width), data[:,3], width, color='#73C2FB', label='Case-4', yerr=data_std[:,3])

ax.set_ylabel('Metric')
ax.set_ylim(0,75)
ax.set_xticks(x + width + width/2)
ax.set_xticklabels(x_labels)
ax.set_xlabel('Scenario')
ax.set_title('Title')
ax.legend()
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

fig.tight_layout()
plt.show()

当您“使用数据[0]传递整个子数组”时,预期的结果是什么?这似乎没有什么意义,所以也许你想解释一下你希望看到的情节是什么样子?@ImportanceOfBeingErnest我用当前的情节更新了这篇文章。正如您所看到的,对于每个场景,所有的条都是相同的。我想更改代码以绘制其他值