How would it look for two columns? For ‘data1a’, ‘data2a’ and ‘data1b’, ‘data2b’? When I try to remove the others I get the error: ValueError: shape mismatch: objects cannot be broadcast to a single shape
JavaScript
x
21
21
1
from matplotlib import pyplot as plt
2
import numpy as np
3
d1label = ['data1a', 'data2a']
4
data1 = [204.24, 224.24]
5
d2label = ['data1b', 'data2b']
6
data2 = [206.24, 226.24]
7
d3label = ['data1c', 'data2c']
8
data3 = [208.24, 228.24]
9
10
width = 0.3
11
12
data = np.concatenate([data1, data2, data3])
13
labels = np.concatenate([d1label, d2label, d3label])
14
colors = np.repeat(["r", "g", "b"], [len(data1), len(data2), len(data3)])
15
idx = np.arange(len(data1))
16
x = np.concatenate([idx, idx+width, idx+width*2])
17
plt.bar(x, data, width=0.3, color=colors)
18
ax = plt.gca()
19
ax.set_xticks(x + width*0.5)
20
ax.set_xticklabels(labels);
21
Reference: matplotlib multiple xticklabel for bar graph
Advertisement
Answer
This ValueError: shape mismatch: objects cannot be broadcast to a single shape
happens because x
and data
should be the same shape. For example, if I take
JavaScript
1
3
1
x = np.concatenate([idx, idx+width, idx+width*2])
2
data = np.concatenate([data1, data2])
3
it will show the error
JavaScript
1
2
1
ValueError: shape mismatch: objects cannot be broadcast to a single shape
2
Just take into account same shape for x
, labels
, color
and data
.
JavaScript
1
10
10
1
data = np.concatenate([data1, data2])
2
labels = np.concatenate([d1label, d2label])
3
colors = np.repeat(["r", "g"], [len(data1), len(data2)])
4
idx = np.arange(len(data1))
5
x = np.concatenate([idx, idx+width])
6
plt.bar(x, data, width=0.3, color=colors)
7
ax = plt.gca()
8
ax.set_xticks(x + width*0.5)
9
ax.set_xticklabels(labels);
10
will output