Как построить сгруппированную гистограмму с неравномерными размерами и с разными категориями? - PullRequest
0 голосов
/ 29 марта 2020

Я очень новичок в создании диаграмм / графиков, и я пытаюсь создать гистограмму из этого набора данных, который я нашел в kaggle: https://www.kaggle.com/sulianova/eda-cardiovascular-data

И я пытаюсь создать групповую диаграмму, которая описывает количество курильщиков / некурящих, пьющих / не пьющих и т. д. c, где у меня есть ось X в качестве возраста, Y для числа и в основном как отдельные бары для мужчины / женщины, а также имеет разделение курящих / некурящих в качестве примера. до сих пор я мог только действительно придумать это ...:

import pandas as pd
import numpy as np
from scipy import stats
from scipy import stats, special
from sklearn import model_selection, metrics, linear_model, datasets, feature_selection, tree
import seaborn as sns
from sklearn.feature_extraction import text  # some text processing tools
from sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB

import matplotlib.pyplot as plt

dataframe = pd.read_csv('cardio_train.csv', sep=';', index_col=0)

dataframe['age_in_years'] = pd.to_numeric(dataframe['age'] / 365).astype(int)

print(dataframe.head())

for column in dataframe.columns.to_list():
    print(column)

# find any NaN rows
nan_row_found = False
for column in dataframe.columns.to_list():
    # print(dataframe.loc[dataframe[column].isnull()])
    nan_row = dataframe.loc[dataframe[column].isnull()]
    if not nan_row.empty:
        nan_row_found = True
        print(nan_row)
print('NaN row found: %s' % nan_row_found)
# data seems to be clean on that front

# cleanup abnormal values
print(dataframe.shape)
dataframe.drop(
                (dataframe[dataframe['height'] < 120].index) | \
                (dataframe[dataframe['height'] > 210].index) | \
                (dataframe[dataframe['ap_lo'] > dataframe['ap_hi']].index) | \
                (dataframe[dataframe['ap_hi'] < 0].index) | \
                (dataframe[dataframe['ap_hi'] > 200].index) | \
                (dataframe[dataframe['ap_lo'] < 0].index) | \
                (dataframe[dataframe['weight'] < 40].index), \
                inplace=True
                )
# dataframe.drop((dataframe[dataframe['height'] < 120].index) | (dataframe[dataframe['ap_lo'] > dataframe['ap_hi']].index) | (dataframe[dataframe['weight'] < dataframe['ap_hi']].index), inplace=True)

# make new dataframe with just patients with cvd
dataframe2 = dataframe.loc[(dataframe['cardio'] == 1)]

# delete the age column because we dont need it anymore
del dataframe2['age']

# make separate dataframes for male, female, and both genders
smokerCount = dataframe2.groupby(['gender', 'smoke']).size().reset_index()
alcoholCount = dataframe2.groupby(['gender', 'alco']).size().reset_index()
activeCount = dataframe2.groupby(['gender', 'active']).size().reset_index()
genderDataframe = pd.DataFrame(index=['Female', 'Male'], columns=['Non-Smoker', 'Smoker', 'Non-Drinker', 'Drinker', 'Sedentary', 'Active'])

genderDataframe.loc[('Female'),('Non-Smoker')] = smokerCount.iloc[0,2]
genderDataframe.loc[('Female'),('Smoker')] = smokerCount.iloc[1,2]
genderDataframe.loc[('Male'),('Non-Smoker')] = smokerCount.iloc[2,2]
genderDataframe.loc[('Male'),('Smoker')] = smokerCount.iloc[3,2]

genderDataframe.loc[('Female'),('Non-Drinker')] = alcoholCount.iloc[0,2]
genderDataframe.loc[('Female'),('Drinker')] = alcoholCount.iloc[1,2]
genderDataframe.loc[('Male'),('Non-Drinker')] = alcoholCount.iloc[2,2]
genderDataframe.loc[('Male'),('Drinker')] = alcoholCount.iloc[3,2]

genderDataframe.loc[('Female'),('Sedentary')] = activeCount.iloc[0,2]
genderDataframe.loc[('Female'),('Active')] = activeCount.iloc[1,2]
genderDataframe.loc[('Male'),('Sedentary')] = activeCount.iloc[2,2]
genderDataframe.loc[('Male'),('Active')] = activeCount.iloc[3,2]

# make habits data by age and gender
dfAgeHabits = dataframe2.copy()
dfAgeHabits['gender'] = dfAgeHabits['gender'].replace({1:'Female',2:'Male'})

# make separate dataframes for male, female, and both genders
smokerAgeCount = dfAgeHabits.groupby(['gender', 'age_in_years', 'smoke']).size().reset_index().rename(columns={0:'count'})
alcoholAgeCount = dfAgeHabits.groupby(['gender', 'age_in_years', 'alco']).size().reset_index().rename(columns={0:'count'})
activeAgeCount = dfAgeHabits.groupby(['gender', 'age_in_years', 'active']).size().reset_index().rename(columns={0:'count'})

smokerAgeCount = smokerAgeCount.sort_values(by='age_in_years')
sns.catplot(x="age_in_years", y="count", hue="gender", data=smokerAgeCount, height=6, kind="bar", palette="muted")
plt.show()

screenshot of current bar chart i have

, что ОЧЕНЬ близко к тому, что я хочу, но это только кажется, что он разделяет мужчину и женщину, как показано в легенде, но нет никаких указаний на то, какой из них является «счетчиком курильщика» / «счетом некурящих»

Как создать диаграмму с этой информацией очень ясно на графике ...?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...