如何使用matplotlib为箱线图添加图片标注?
箱线图添加图片标注实现方案
你原有代码存在3处可调整的问题:
fig, ax = plt.subplots漏写了方法调用的右括号- 按
name分组绘制箱线图时,每个分类对应的x轴坐标为1~6(对应6个名字的顺序),不是固定为0 - 不要取分组内第一个
A值作为标注的y坐标,建议取分组最大值/中位数/均值,避免标注遮挡箱线图元素
修正后的完整可运行代码如下:
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.offsetbox import OffsetImage, AnnotationBbox from matplotlib.cbook import get_sample_data # 生成测试数据 names = ['PersonA', 'PersonB', 'PersonC', 'PersonD','PersonE','PersonF'] regions = ['NorthEast','NorthWest','SouthEast','SouthWest'] dates = pd.date_range(start = '2021-05-28', end = '2021-08-23', freq = 'D') df = pd.DataFrame({'runtime': np.repeat(dates, len(names))}) df['name'] = len(dates)*names df['A'] = 40 + 20*np.random.random(len(df)) df['B'] = .1 * np.random.random(len(df)) df['C'] = 1 +.5 * np.random.random(len(df)) df['region'] = np.resize(regions,len(df)) # 绘制箱线图+添加图片标注 fig, ax = plt.subplots(figsize=(10,6)) df.boxplot(column='A', by=['name'],ax=ax,showmeans=True, fontsize=8, grid=False) plt.title('箱线图加头像标注示例') plt.suptitle('') # 去掉pandas自动生成的子标题 # 遍历每个name添加标注 for idx, name in enumerate(names): # 取对应分组的最大值作为标注y坐标,也可以替换成.mean()/.median()按需调整 val = df[df['name']==name]['A'].max() # x坐标为索引+1,因为pandas箱线图分组坐标从1开始计数 xy = (idx + 1, val) # 加载对应头像图片 fn = get_sample_data(f"{name}.png", asfileobj=False) arr_img = plt.imread(fn, format='png') imagebox = OffsetImage(arr_img, zoom=0.125) imagebox.image.axes = ax # 调整xybox的y偏移,让图片在箱线图上方显示 ab = AnnotationBbox(imagebox, xy, xybox=(0, 20), xycoords='data', boxcoords="offset points", pad=0, frameon=False) ax.add_artist(ab) plt.ylim(38, 65) # 调整y轴范围避免顶部图片被截断 plt.show()
用到的示例头像资源:


内容的提问来源于stack exchange,提问作者p3hndrx
相关产品推荐
相关产品推荐

