我想向箱线图添加图像注释,类似于他们在这篇文章中对条形图所做的: How can I add images to bars in axes (matplotlib)
我的数据框是这样的:
import pandas as pd
import numpy as np
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))
我尝试使用非常适合我的时间序列的 AnnotationBbox 方法,但我不完全确定它是否可以在这里应用。
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from matplotlib.cbook import get_sample_data
fig, ax = plt.subplots(
df.boxplot(column='A', by=['name'],ax=ax,showmeans=True, fontsize=8, grid=False)
for name in names:
rslt_df = df[df['name']==name]
val = rslt_df['A'].values[0]
xy = (0, 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
ab = AnnotationBbox(imagebox, xy,xybox=(15.,0),xycoords='data',boxcoords="offset points",pad=0,frameon=False)
ax.add_artist(ab)
最佳答案
- OP 中的代码与 Add image annotations to bar plots axis tick labels 非常相似, 但需要修改,因为
boxplots
与barplots
略有不同。 - 主要问题是
xy
没有正确的值。- 可以调整
xy
和xybox
参数以将图像放置在任何位置。
- 可以调整
- 默认情况下,
boxplot
将刻度定位在range(1, n+1)
中,如 answer 中所述- 用 0 索引重置刻度位置:
positions=range(len(names))
- 用 0 索引重置刻度位置:
df
是使用names = ['PersonA', 'PersonB', 'PersonC']
创建的,因为只提供了 3 张图像。
ax = df.boxplot(column='A', by=['name'], showmeans=True, fontsize=8, grid=False, positions=range(len(names)))
ax.set(xlabel=None, title=None)
# move the xtick labels
ax.set_xticks(range(len(names)))
ax.set_xticklabels(countries)
ax.tick_params(axis='x', which='major', pad=30)
# use the ytick values to locate the image
y = ax.get_yticks()[1]
for i, (name, data) in enumerate(df.groupby('name')):
xy = (i, y)
fn = f"data/so_data/2021-08-28/{name}.png" # path to file
arr_img = plt.imread(fn, format='png')
imagebox = OffsetImage(arr_img, zoom=0.125)
imagebox.image.axes = ax
ab = AnnotationBbox(imagebox, xy, xybox=(0, -30), xycoords='data', boxcoords="offset points", pad=0, frameon=False)
ax.add_artist(ab)
关于python - 将图像注释添加到箱线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68965009/