数据编码的重要性:
- 数据可视化的目的是更容易地传达信息(例如,在这种情况下,每个类别的
'treatments' 的相对数量)
- 条形图可轻松显示重要信息
- 每组有多少人说
'Yes' 或'No'
- 每组的相对大小
- 饼图更常用于显示样本,其中样本中的组总和为 100%。
-
Wikipedia: Pie Chart
- 研究表明,按角度比较不如按长度比较准确,因为人们无法辨别差异。
-
Statisticians 普遍认为饼图是一种糟糕的信息显示方式,在科学文献中并不常见。
- 饼图不能很好地表示此数据,因为每个公司规模都是一个单独的总体,这需要 6 个饼图才能正确表示。
- 数据可以像其他人所展示的那样放入饼图中,但这并不意味着它应该如此。
- 无论绘图类型如何,数据的形状都必须适合绘图 API。
- 使用
pandas 1.3.0、seaborn 0.11.1 和matplotlib 3.4.2 测试
设置测试数据帧
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np # for sample data only
np.random.seed(365)
cats = ['1-5', '6-25', '26-100', '100-500', '500-1000', '>1000']
data = {'no_employees': np.random.choice(cats, size=(1000,)),
'treatment': np.random.choice(['Yes', 'No'], size=(1000,))}
df = pd.DataFrame(data)
# set a categorical order for the x-axis to be ordered
df.no_employees = pd.Categorical(df.no_employees, categories=cats, ordered=True)
no_employees treatment
0 26-100 No
1 1-5 Yes
2 >1000 No
3 100-500 Yes
4 500-1000 Yes
# to get the dataframe in the correct shape, unstack the groupby result
dfu = df.groupby(['no_employees']).treatment.value_counts().unstack()
treatment No Yes
no_employees
1-5 78 72
6-25 83 86
26-100 83 76
100-500 91 84
500-1000 78 83
>1000 95 91
# plot
ax = dfu.plot(kind='bar', figsize=(7, 5), xlabel='Number of Employees in Company', ylabel='Count', rot=0)
ax.legend(title='treatment', bbox_to_anchor=(1, 1), loc='upper left')
用seaborn绘图
# groupby, get value_counts, and reset the index
dft = df.groupby(['no_employees']).treatment.value_counts().reset_index(name='Count')
no_employees treatment Count
0 1-5 No 78
1 1-5 Yes 72
2 6-25 Yes 86
3 6-25 No 83
4 26-100 No 83
5 26-100 Yes 76
6 100-500 No 91
7 100-500 Yes 84
8 500-1000 Yes 83
9 500-1000 No 78
10 >1000 No 95
11 >1000 Yes 91
# plot
p = sns.barplot(x='no_employees', y='Count', data=dft, hue='treatment')
p.legend(title='treatment', bbox_to_anchor=(1, 1), loc='upper left')
p.set(xlabel='Number of Employees in Company')
p = sns.countplot(data=df, x='no_employees', hue='treatment')
p.legend(title='treatment', bbox_to_anchor=(1, 1), loc='upper left')
p.set(xlabel='Number of Employees in Company')