我有以下代码来生成catplot:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Import data
df = pd.read_csv('numpy_pandas\data\medical_examination.csv')
# Add 'overweight' column
# Use np.where
df['overweight'] = np.where(df['weight']/pow(df['height']/100, 2) > 25, True, False)
# Normalize data by making 0 always good and 1 always bad. If the value of 'cholesterol' or 'gluc' is 1, make the value 0. If the value is more than 1, make the value 1.
df.loc[:, ['cholesterol', 'gluc']] = np.where(df.loc[:, ['cholesterol', 'gluc']] > 1, 1, 0)
# Draw Categorical Plot
def draw_cat_plot():
# Create DataFrame for cat plot using `pd.melt` using just the values from 'cholesterol', 'gluc',
# 'smoke', 'alco', 'active', and 'overweight'.
df_cat = df.melt(id_vars=['cardio'],
value_vars=['cholesterol', 'gluc', 'smoke',
'alco', 'active', 'overweight'])
# Group and reformat the data to split it by 'cardio'. Show the counts of each feature.
df_cat = df_cat.groupby(['cardio', 'variable', 'value'])['variable'].count().reset_index(name='total')
# Draw the catplot with 'sns.catplot()'
# Get the figure for the output
fig = sns.catplot(data=df_cat, x='variable', y='total', col='cardio',
kind='bar')
# Export the figure
fig.savefig('catplot.png')
return fig
draw_cat_plot()
如何修复我的绘图以生成更像上面绘图的东西?
我正在使用一些虚拟数据,但您可以使用
hue
参数创建图表并将 errorbar
设置为 None
。
# generate Dummy data:
import pandas as pd
import seaborn as sns
import numpy as np
n = 50
choice = ['a', 'b', 'c']
df = pd.DataFrame({
'cardio': np.random.randint(0,2,n),
'value': np.random.randint(0,2,n),
'total': np.random.randint(1000, 100000,n),
'variable': np.random.choice(choice, size = n, replace=True )
})
剧情:
sns.catplot(df,x='variable', y='total', col='cardio',
kind='bar',errorbar=None, hue = 'value' )