如何在Matplotlib Violin Plot中标注最值、均值及中位数数值?
给Matplotlib小提琴图标注最值、均值的实现方法
问题背景
现有生成小提琴图的代码,需要在图上为最小值、最大值及均值对应的线条标注具体数值,已知将violinplot赋值给变量后可访问cmaxes等属性,但不清楚如何利用这些属性完成标注,预期效果为在各统计线旁显示对应数值。
解决方案
核心思路是通过violinplot返回的对象获取各统计线的坐标,再结合annotate方法完成数值标注,具体实现如下:
修改后的完整代码
import pandas as pd import matplotlib.pyplot as plt data = 'https://raw.githubusercontent.com/marsja/jupyter/master/flanks.csv' df = pd.read_csv(data, index_col=0) # 数据分组 congruent = df.query('TrialType == "congruent"')['RT'] incongruent = df.query('TrialType == "incongruent"')['RT'] plot_data = [incongruent, congruent] fig, ax = plt.subplots() # 设置坐标轴标签 xticklabels = ['Incongruent', 'Congruent'] ax.set_xticks([1, 2]) ax.set_xticklabels(xticklabels) # 绘制小提琴图,开启均值、最值线显示,并获取绘图元素 violin_parts = ax.violinplot(plot_data, showmedians=True, showmeans=True, showextrema=True) # 定义标注样式 annotate_kwargs = {'xytext': (10, 0), 'textcoords': 'offset points', 'fontsize': 9} # 遍历每个分组,标注最大值、最小值、均值 for i in range(len(plot_data)): # 获取当前分组的统计线坐标 max_y = violin_parts['cmaxes'].get_ydata()[i] min_y = violin_parts['cmins'].get_ydata()[i] mean_y = violin_parts['cmeans'].get_ydata()[i] x_pos = i + 1 # 对应小提琴图的x轴位置 # 标注最大值 ax.annotate(f'{max_y:.1f}', xy=(x_pos, max_y), **annotate_kwargs) # 标注最小值 ax.annotate(f'{min_y:.1f}', xy=(x_pos, min_y), **annotate_kwargs) # 标注均值 ax.annotate(f'{mean_y:.1f}', xy=(x_pos, mean_y), **annotate_kwargs) plt.show()
关键说明
- 开启统计线显示:调用
violinplot时必须传入showmeans=True和showextrema=True,否则无法生成均值、最值线,也就无法获取对应的坐标数据 - 获取统计线坐标:
violin_parts字典中,cmaxes对应最大值线、cmins对应最小值线、cmeans对应均值线,通过get_ydata()可提取这些线条的y轴数值(即统计值) - 标注位置调整:通过
xytext参数设置标注文本相对于线条的偏移量,避免文本与线条重叠,f'{value:.1f}'用于格式化数值为1位小数,提升可读性
内容的提问来源于stack exchange,提问作者piehighnoon
相关产品推荐
相关产品推荐

