自动查找并添加坐标,以便在由不均匀列表字典生成的Boxplot上添加注释(例如count)



我是一个编程新手,我真的很沮丧地解决了一个问题,我认为这应该是非常容易的…

情况:假设我有一个列表不均匀的字典;还有键的数量(字符串)&数值(数字)可以随时改变。

需要:我想注释(添加文本或其他)一些信息(例如计数)到每个子情节或类别(每个关键是一个单独的类别)。

问题:我找到了许多针对均匀编号类别的解决方案,但显然对我不起作用。如解决方案

我也找到了一些答案,例如解决方案,我应该首先得到x线上每个键的坐标,然后做一个反向变换来处理"对数刻度"。这对我来说是迄今为止最好的解决方案,但不幸的是,它并不真正适合坐标,我无法得到&在使用plt.show()之前自动添加点。

我也可以用变换方法中的试错来猜测坐标,或者用偏移量例如解决方案。但是就像我说的,我的字典可以随时改变,然后我应该每次都重新做一遍!

我想应该有更简单的方法来解决这个问题,但是我找不到。

下面是我的代码和我尝试的简化示例:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
AnnotationBbox)
dictionary = {}
dictionary["a"] = [1, 2, 3, 4, 5]
dictionary["b"] = [1, 2, 3, 4, 5, 6, 7]
fig, ax = plt.subplots()
ax.boxplot(dictionary.values())
x = ax.set_xticklabels(dictionary.keys())
fig.text(x = 0.25, y = 0, s = str(len(dictionary["a"])))
fig.text(x = 0.75, y = 0, s = str(len(dictionary["b"])))

plt.show()

crd = np.vstack((ax.get_xticks(), np.zeros_like(ax.get_xticks()))).T
ticks = ax.transAxes.inverted().transform(ax.transData.transform(crd))
print(ticks[:,0])

# ab = AnnotationBbox(TextArea("text"), xy=(1, 0), xybox =(0, -30), boxcoords="offset points",pad=0,frameon=False )
# ax.add_artist(ab)

我的代码输出

据我所知,您可能想要这样的东西:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
AnnotationBbox)
dictionary = {}
dictionary["a"] = [1, 2, 3, 4, 5]
dictionary["b"] = [1, 2, 3, 4, 5, 6, 7]
dictionary["cex"] = [1, 2, 3]
fig, ax = plt.subplots()
ax.boxplot(dictionary.values())
x = ax.set_xticklabels(dictionary.keys())
ticksList=ax.get_xticks()
print (ticksList)
for x in ticksList:
ax.text(x, 0,str(len(list(dictionary.values())[x-1])),fontdict={'horizontalalignment': 'center'})
fig.show()

最新更新