SCI,CCF,EI及核心期刊绘图宝典,爆款持续更新,助力科研!
本期分享:
【SCI绘图】【小提琴系列1 python】绘制按分类变量分组的垂直小提琴图,文末附完整代码
小提琴图是一种常用的数据可视化工具,它结合了箱形图和密度图的特点,用于展示数据的分布情况和变化趋势。其外形类似于小提琴,因而得名。
1.环境准备
python
import seaborn as sns
import matplotlib.pyplot as plt
2.示例数据
python
# 记载数据
tips = sns.load_dataset("tips")
数据样例:
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
3.绘图展示
python
# 绘制一个按分类变量分组的垂直小提琴图
fig = sns.violinplot(x="day", y="total_bill", data=tips)
plt.show()
# 保存箱型图
output_fig = fig.get_figure()
output_fig.savefig("violin_plot.png", dpi=400)
完整代码:
python
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")
# 记载数据
tips = sns.load_dataset("tips")
print(tips[:5])
"""
数据样例:
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
"""
# 绘制一个按分类变量分组的垂直小提琴图
fig = sns.violinplot(x="day", y="total_bill", data=tips)
plt.show()
# 保存箱型图
output_fig = fig.get_figure()
output_fig.savefig("violin_plot.png", dpi=400)