分布(四)利用python绘制小提琴图
小提琴图 (Violin plot)简介
小提琴图主要用于显示数据分布及其概率密度。中间的黑色粗条表示四分位数范围,从其延伸的幼细黑线代表 95% 置信区间(以外则为异常点),而白点则为中位数。小提琴图结合了箱线图和密度图的优点,既可以了解数据统计信息,也可以了解数据分布特点。
快速绘制
-
基于seaborn
import seaborn as sns import matplotlib.pyplot as plt sns.set(style="darkgrid") # 导入数据 df = sns.load_dataset('iris') # 利用violinplot函数绘制小提琴图 sns.violinplot(x=df["species"], y=df["sepal_length"]) plt.show()
定制多样化的小提琴图
自定义小提琴图一般是结合使用场景对相关参数进行修改,并辅以其他的绘图知识。参数信息可以通过官网进行查看,其他的绘图知识则更多来源于实战经验,大家不妨将接下来的绘图作为一种学习经验,以便于日后总结。
seaborn主要利用violinplot
绘制小提琴图,可以通过seaborn.violinplot了解更多用法
- 绘制多个小提琴图
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(font='SimHei', font_scale=0.8, style="darkgrid") # 解决Seaborn中文显示问题
# 导入数据
df = sns.load_dataset('iris')
df_tips = sns.load_dataset('tips')
fig, ax = plt.subplots(1,3, figsize=(12,4))
# 多个数值变量的小提琴图
sns.violinplot(data=df.iloc[:,0:2], ax=ax[0])
ax[0].set_title('多个数值变量')
# 一个数值变量多个分组的小提琴图
sns.violinplot( x=df["species"], y=df["sepal_length"], ax=ax[1] )
ax[1].set_title('一个数值变量多个分组')
# 一个数值变量多个分组子分组的小提琴图
sns.violinplot(x="day", y="total_bill"