欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > python制图之小提琴图

python制图之小提琴图

2025/2/24 0:35:26 来源:https://blog.csdn.net/pianmian1/article/details/145786755  浏览:    关键词:python制图之小提琴图

提琴图(Violin Plot)是一种结合了箱线图(Box Plot)和核密度估计(Kernel Density Estimation, KDE)的可视化工具,用于展示数据的分布情况和概率密度。它在数据可视化中具有独特的作用.本节我们学习如何使用python绘制提琴图

# 导入所需的库
import matplotlib.pyplot as plt  # 用于绘图
import numpy as np  # 用于数值计算
import pandas as pd  # 用于数据处理和分析
import seaborn as sns  # 用于高级数据可视化
import matplotlib as mpl  # Matplotlib 的底层库,用于调整绘图参数
import warnings  # 用于处理警告信息# 忽略警告
warnings.filterwarnings("ignore")  # 忽略运行代码时可能出现的警告,使输出更简洁# 恢复默认的 Matplotlib 设置
mpl.rcParams.update(mpl.rcParamsDefault)  # 将 Matplotlib 的参数恢复为默认值,避免之前设置的影响
sns.set_style("white")  # 设置 Seaborn 的绘图风格为白色背景# 示例数据
data = {"Age": ["18-24", "18-24", "25-34", "25-34", "35-44", "35-44", "45-54", "45-54", "55+", "55+"],  # 年龄组"Unemployed": [120, 150, 90, 100, 80, 95, 70, 85, 60, 75],  # 各年龄组的失业人数"Gender": ["Male", "Female", "Male", "Female", "Male", "Female", "Male", "Female", "Male", "Female"]  # 性别
}# 将数据保存为 Excel 文件
employment = pd.DataFrame(data)  # 将字典数据转换为 Pandas DataFrame
employment.to_excel("unemployment.xlsx", index=False)  # 将 DataFrame 保存为 Excel 文件,不保存索引# 读取数据
employment = pd.read_excel("unemployment.xlsx")  # 从 Excel 文件中读取数据# 绘制提琴图
sns.violinplot(x=employment.Age,  # x 轴为年龄组y=employment.Unemployed,  # y 轴为失业人数hue=employment.Gender,  # 按性别分组并着色palette='Set2'  # 使用 Seaborn 的 Set2 调色板
)
plt.show()  # 显示图形

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词