ValueError: shape mismatch: objects cannot be broadcast to a single shape when plotting a bar
ValueError: shape mismatch: objects cannot be broadcast to a single shape when plotting a bar
我试着画了条形图。
purchase_value
Buy_Coffee
Buy_ColdDrinks
Buy_Juices
Buy_Pastries
Buy_Sandwiches
0
0
1
0
1
0
1
1
0
0
0
0
2
1
0
0
0
1
3
1
0
0
0
0
4
1
0
0
0
1
5
1
0
0
0
0
plt.bar(purchase_value.index,
purchase_value.value_counts(),
width=0.5,
bottom=None,
align='center',
color=['lightsteelblue',
'cornflowerblue',
'royalblue',
'midnightblue',
'darkblue'])
plt.xticks(rotation='vertical')
plt.show()
但是结果
ValueError: shape mismatch: objects cannot be broadcast to a single shape
当您调用 pandas.DataFrame.value_counts
时,您正在计算行值的每个唯一组合的计数。
因此,通过将其应用于您提供的数据,您将获得:
Buy_Coffee Buy_ColdDrinks Buy_Juices Buy_Pastries Buy_Sandwiches
1 0 0 0 0 3
1 2
0 1 0 1 0 1
组合的数量可能不等于数据中的行数 (purchase_value.index
)。
如果我理解正确你想绘制什么,你应该使用:
import pandas as pd
import matplotlib.pyplot as plt
purchase_value = pd.read_csv(r'data/data.csv')
fig, ax = plt.subplots()
purchase_value.plot(kind = 'bar',
ax = ax,
stacked = True,
width=0.5,
bottom=0,
align='center',
color=['lightsteelblue',
'cornflowerblue',
'royalblue',
'midnightblue',
'darkblue'])
plt.show()
如果要为每列绘制每个项目的总和,您应该使用:
fig, ax = plt.subplots()
purchase_value.sum(axis = 0).plot(kind = 'bar',
ax = ax,
stacked = True,
width=0.5,
bottom=0,
align='center',
color=['lightsteelblue',
'cornflowerblue',
'royalblue',
'midnightblue',
'darkblue'])
plt.tight_layout()
plt.show()
我试着画了条形图。
purchase_value
Buy_Coffee | Buy_ColdDrinks | Buy_Juices | Buy_Pastries | Buy_Sandwiches | |
---|---|---|---|---|---|
0 | 0 | 1 | 0 | 1 | 0 |
1 | 1 | 0 | 0 | 0 | 0 |
2 | 1 | 0 | 0 | 0 | 1 |
3 | 1 | 0 | 0 | 0 | 0 |
4 | 1 | 0 | 0 | 0 | 1 |
5 | 1 | 0 | 0 | 0 | 0 |
plt.bar(purchase_value.index,
purchase_value.value_counts(),
width=0.5,
bottom=None,
align='center',
color=['lightsteelblue',
'cornflowerblue',
'royalblue',
'midnightblue',
'darkblue'])
plt.xticks(rotation='vertical')
plt.show()
但是结果
ValueError: shape mismatch: objects cannot be broadcast to a single shape
当您调用 pandas.DataFrame.value_counts
时,您正在计算行值的每个唯一组合的计数。
因此,通过将其应用于您提供的数据,您将获得:
Buy_Coffee Buy_ColdDrinks Buy_Juices Buy_Pastries Buy_Sandwiches
1 0 0 0 0 3
1 2
0 1 0 1 0 1
组合的数量可能不等于数据中的行数 (purchase_value.index
)。
如果我理解正确你想绘制什么,你应该使用:
import pandas as pd
import matplotlib.pyplot as plt
purchase_value = pd.read_csv(r'data/data.csv')
fig, ax = plt.subplots()
purchase_value.plot(kind = 'bar',
ax = ax,
stacked = True,
width=0.5,
bottom=0,
align='center',
color=['lightsteelblue',
'cornflowerblue',
'royalblue',
'midnightblue',
'darkblue'])
plt.show()
如果要为每列绘制每个项目的总和,您应该使用:
fig, ax = plt.subplots()
purchase_value.sum(axis = 0).plot(kind = 'bar',
ax = ax,
stacked = True,
width=0.5,
bottom=0,
align='center',
color=['lightsteelblue',
'cornflowerblue',
'royalblue',
'midnightblue',
'darkblue'])
plt.tight_layout()
plt.show()