Pandas 条形图未分组在一起

Pandas 条形图未分组在一起,pandas,dataframe,matplotlib,Pandas,Dataframe,Matplotlib,我想创建一个条形图,其中“Age_round”按升序分组。现在所有的酒吧都分开了 import matplotlib.pyplot as plt df.plot(kind='bar',x='Age_round',y='number of purchased hours(mins)') plt.xlabel('Age_round') plt.ylabel('number of purchased hours(mins)') # plt.xticks(np.arange(start = 4, sto

我想创建一个条形图,其中“Age_round”按升序分组。现在所有的酒吧都分开了

import matplotlib.pyplot as plt
df.plot(kind='bar',x='Age_round',y='number of purchased hours(mins)')
plt.xlabel('Age_round')
plt.ylabel('number of purchased hours(mins)')
# plt.xticks(np.arange(start = 4, stop = 17, step = 1))
plt.title('Age Distribution Graph')
plt.grid()
下面是我的数据框

    Package Age_round   gender
1   7000    9.0 1
2   7000    10.0    0
3   5000    9.0 0
4   9000    10.0    1
5   3000    12.0    1
6   5000    9.0 1
7   9000    10.0    1
8   6000    16.0    1
9   6000    12.0    0
10  6000    7.0 1
11  12000   7.0 1
12  12000   15.0    1
13  6000    10.0    1


基本上,我想创建一个条形图,其中x轴为“年龄轮”,y轴显示频率,而“包装”则由不同颜色的条形图区分。我写了一段代码来完成这项工作,不确定这是否是最好的方法:

制作一个新的DF,根据包读取每个年龄段的频率数据,并指定“值(年龄)”作为其索引

values = df.Age_round.unique()
values.sort()

newdf = pd.DataFrame()  

for x in values : 
    freq_x = df[df['Age_round']==x]['Package'].value_counts()
    newdf = newdf.append(freq_x)

newdf.index = values
newdf.plot(kind='bar',stacked=True, figsize=(15,6))

以下是一个可能的实现:

将熊猫作为pd导入
将matplotlib.pyplot作为plt导入
df=pd.DataFrame(列=['Package','Age\u round','gender'],
数据=[[7000,9.0,1],[7000,10.0,0],[5000,9.0,0],[9000,10.0,1],[3000,12.0,1],
[5000, 9.0, 1], [9000, 10.0, 1], [6000, 16.0, 1], [6000, 12.0, 0], [6000, 7.0, 1],
[12000, 7.0, 1], [12000, 15.0, 1], [6000, 10.0, 1]])
df['Age_round']=df['Age_round'].astype(int)#可选地将数字四舍五入为整数
df.sort_值(['Age_round','Package'])。绘图(kind='bar',x='Age_round',y='Package',rot=0,color='deeppink')
plt.xlabel(‘年龄(四舍五入)’)
plt.ylabel(‘购买的小时数(分钟)’)
产品名称(“年龄分布图”)
plt.grid(真,轴='y')
plt.show()