亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從計數圖創建單獨的 distplot

從計數圖創建單獨的 distplot

蝴蝶刀刀 2023-02-07 17:24:50
如何從 countplot 創建 distplotplt.rcdefaults()%config InlineBackend.figure_format='retina'sns.set_style('darkgrid')ax = sns.countplot(x='Age',hue='Gender',data=df,edgecolor="None")ax.tick_params(bottom=False, left=False)ax.set_axisbelow(True)for rect in ax.patches:        x = rect.get_x() + rect.get_width()/2.        y = rect.get_height()        try:            ax.annotate("{}".format(int(y)), (x,y), ha='center', va='bottom', clip_on=True)        except:            passax.set_xlabel('Age', color='green')ax.set_ylabel('Count', color='green')ax.set_title('Countplot for Age(Gender)', color='tomato',weight='bold')plt.legend(title='Gender', fontsize='large', loc='upper right').get_frame().set_facecolor('white')plt.tight_layout()plt.savefig('files\\Countplot_for_Age(Gender).jpg')
查看完整描述

1 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

a 的 x 軸countplot是分類的:它為每個遇到的年齡放置一個條,當沒有特定年齡的行時跳過條(示例中為 21 和 23)。在內部,條形編號為 0、1、2、...。y 軸是計數,與行數成正比。


對于 a distplot,x 軸是年齡本身,y 軸是概率分布,通常是非常小的數字(曲線下面積標準化為 1)。


因此,由于 x 軸和 y 軸不同,最好使用單獨的子圖。


Adistplot可以直接從給定的數據生成。ax在同一子圖中的兩個distplots 中傳遞相同的結果。Adistplot是直方圖和 a 的組合kdeplot。如果不需要直方圖, 可以hist=False省略

,或者kdeplot直接調用。該shade=True選項向繪圖添加陰影。


from matplotlib import pyplot as plt

import seaborn as sns

import pandas as pd

import numpy as np


NF = 50

NM = 10

df = pd.DataFrame({'Age': np.concatenate([np.random.randint(13, 20, NF) + np.random.randint(2, 7, NF),

                                          np.random.randint(15, 23, NM)]),

                   'Gender': np.repeat(['female', 'male'], (NF, NM))})

df['Age'] = df['Age'].where((df['Age'] != 21) & (df['Age'] != 23), 20)


sns.set_style('darkgrid')


fig, axs = plt.subplots(ncols=2, figsize=(12, 4))


ax = sns.countplot(x='Age', hue='Gender', data=df, edgecolor="None", ax=axs[0])

ax.tick_params(bottom=False, left=False)

ax.set_axisbelow(True)


for rect in ax.patches:

    x = rect.get_x() + rect.get_width() / 2.

    y = rect.get_height()

    ax.annotate(f"{y:.0f}", (x, y), ha='center', va='bottom', clip_on=True)


ax.set_xlabel('Age', color='green')

ax.set_ylabel('Count', color='green')

ax.set_title('Countplot for Age(Gender)', color='tomato', weight='bold')

ax.legend(title='Gender', fontsize='large', loc='upper right').get_frame().set_facecolor('white')


for gender in ('female', 'male'):

    # ax2 = sns.kdeplot(df[df['Gender'] == gender]['Age'], shade=True, ax=axs[1], label=gender)

    ax2 = sns.distplot(df[df['Gender'] == gender]['Age'], hist=False, kde_kws={'shade': True}, ax=axs[1], label=gender)


ax2.set_axisbelow(True)

ax2.set_xlabel('Age', color='green')

ax2.set_ylabel('probability distribution', color='green')

ax2.set_title('Distplot for Age(Gender)', color='tomato', weight='bold')

ax2.legend(title='Gender', fontsize='large', loc='upper right').get_frame().set_facecolor('white')


plt.tight_layout()

plt.show()

http://img1.sycdn.imooc.com//63e2191e00018da725600822.jpg

查看完整回答
反對 回復 2023-02-07
  • 1 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號