将小提琴图中的均值指示器更改为圆圈

Change mean indicator in violin plot to a circle

我想更改小提琴图中均值的外观。我正在使用 matplotlib。我可以使用以下代码更改方法的颜色:

 import matplotlib.pyplot as plt

 fig,(axes1,axes2,axes3) = plt.subplots(nrows=3,ncols=1,figsize=(10,20))

 r=axes2.violinplot(D,showmeans=True,showmedians=True)
 r['cmeans'].set_color('red')

但现在我想将均值(目前是一条线,如中位数)的外观更改为 'small circle'。 有人可以帮我解决这个问题吗?

想法可以是获取平均线的坐标并在这些坐标处绘制散点图。

获取坐标可以

  • 要么通过遍历平均线的路径来完成,

    # loop over the paths of the mean lines
    xy = [[l.vertices[:,0].mean(),l.vertices[0,1]] for l in r['cmeans'].get_paths()]
    xy = np.array(xy)
    
  • 或通过重新计算输入数据的平均值。

    #alternatively get the means from the data
    y = data.mean(axis=0)
    x = np.arange(1,len(y)+1)
    xy=np.c_[x,y] 
    

完整代码:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

data = np.random.normal(size=(50, 2))

fig,ax = plt.subplots()

r=ax.violinplot(data,showmeans=True)

# loop over the paths of the mean lines
xy = [[l.vertices[:,0].mean(),l.vertices[0,1]] for l in r['cmeans'].get_paths()]
xy = np.array(xy)
##alternatively get the means from the data
#y = data.mean(axis=0)
#x = np.arange(1,len(y)+1)
#xy=np.c_[x,y] 

ax.scatter(xy[:,0], xy[:,1],s=121, c="crimson", marker="o", zorder=3)

# make lines invisible
r['cmeans'].set_visible(False)

plt.show()