创建使用百分比而不是计数的matplotlib或seaborn直方图?

2024-04-19 18:38:25 发布

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

特别是我在处理Kaggle泰坦尼克号的数据集。我绘制了一个堆积的柱状图,显示了泰坦尼克号上幸存和死亡的年代。代码如下。

figure = plt.figure(figsize=(15,8))
plt.hist([data[data['Survived']==1]['Age'], data[data['Survived']==0]['Age']], stacked=True, bins=30, label=['Survived','Dead'])
plt.xlabel('Age')
plt.ylabel('Number of passengers')
plt.legend()

我想修改图表,以显示该年龄组每箱存活百分比的一个图表。E、 如果一个箱子里装着10-20岁之间的人,而泰坦尼克号上60%的人在这个年龄段幸存下来,那么这个箱子的高度将沿着y轴排列成60%。

编辑:我可能没有很好地解释我要找的东西。我不想改变y轴的值,而是希望根据存活的百分比来改变钢筋的实际形状。

图中的第一个箱子显示大约65%的人在这个年龄组存活下来。我想让这个箱子以65%的速度与y轴对齐。下面的垃圾箱看起来分别是90%、50%、10%,依此类推。

这张图最终看起来像这样:

enter image description here


Tags: 数据代码agedata图表绘制pltfigure
3条回答

pd.Series.hist在下面使用np.histogram

让我们来探索一下

np.random.seed([3,1415])
s = pd.Series(np.random.randn(100))
d = np.histogram(s, normed=True)
print('\nthese are the normalized counts\n')
print(d[0])
print('\nthese are the bin values, or average of the bin edges\n')
print(d[1])

these are the normalized counts

[ 0.11552497  0.18483996  0.06931498  0.32346993  0.39278491  0.36967992
  0.32346993  0.25415494  0.25415494  0.02310499]

these are the bin edges

[-2.25905503 -1.82624818 -1.39344133 -0.96063448 -0.52782764 -0.09502079
  0.33778606  0.77059291  1.20339976  1.6362066   2.06901345]

我们可以在计算平均垃圾箱边缘时绘制这些图

pd.Series(d[0], pd.Series(d[1]).rolling(2).mean().dropna().round(2).values).plot.bar()

enter image description here

实际答案
或者

我们可以简单地将normed=True传递给pd.Series.hist方法。把它传给np.histogram

s.hist(normed=True)

enter image description here

首先,最好创建一个函数,将数据按年龄分组

# This function splits our data frame in predifined age groups
def cutDF(df):
    return pd.cut(
        df,[0, 10, 20, 30, 40, 50, 60, 70, 80], 
        labels=['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80'])


data['AgeGroup'] = data[['Age']].apply(cutDF)

然后可以按如下方式绘制图形:

survival_per_age_group = data.groupby('AgeGroup')['Survived'].mean()

# Creating the plot that will show survival % per age group and gender
ax = survival_per_age_group.plot(kind='bar', color='green')
ax.set_title("Survivors by Age Group", fontsize=14, fontweight='bold')
ax.set_xlabel("Age Groups")
ax.set_ylabel("Percentage")
ax.tick_params(axis='x', top='off')
ax.tick_params(axis='y', right='off')
plt.xticks(rotation='horizontal')             

# Importing the relevant fuction to format the y axis 
from matplotlib.ticker import FuncFormatter

ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: '{:.0%}'.format(y)))
plt.show()

也许以下几点会有帮助。。。

  1. 基于“存活”拆分数据帧

    df_survived=df[df['Survived']==1]
    df_not_survive=df[df['Survived']==0]
    
  2. 创建箱子

    age_bins=np.linspace(0,80,21)
    
  3. 使用np.histogram生成直方图数据

    survived_hist=np.histogram(df_survived['Age'],bins=age_bins,range=(0,80))
    not_survive_hist=np.histogram(df_not_survive['Age'],bins=age_bins,range=(0,80))
    
  4. 计算每个箱子的存活率

    surv_rates=survived_hist[0]/(survived_hist[0]+not_survive_hist[0])
    
  5. 情节

    plt.bar(age_bins[:-1],surv_rates,width=age_bins[1]-age_bins[0])
    plt.xlabel('Age')
    plt.ylabel('Survival Rate')
    

enter image description here

相关问题 更多 >