如何使用matplotlib改变一个坐标轴中每个小提琴图的中线颜色?

kzipqqlq  于 2023-02-23  发布在  其他
关注(0)|答案(1)|浏览(246)

This is my code:

fig, ax = plt.subplots()
parts = ax.violinplot([df1_1['Height'], df1_2['Height'], df1_3['Height']], showmedians=True, vert=False, points=1000, widths=1, showextrema=False)
ax.set_title('Height Distributions (2000 - 2016 Olympics)')

ax.set_yticks([1, 2, 3])
ax.set_yticklabels(['Gymnastics', 'Cycling', 'Basketball'])

parts['bodies'][0].set_color('purple')
parts['bodies'][1].set_color('green')
parts['bodies'][2].set_color('blue')

parts['bodies'][0].set_linewidth(1.25)
parts['bodies'][1].set_linewidth(1.25)
parts['bodies'][2].set_linewidth(1.25)

# set the medians color for each violin
parts['cmedians'].set_color('blue')
parts['cmedians'].set_linewidth(1.25)

plt.show()

And this is my output:

However, this is the output that I want:

The only thing that is diff is the median lines' colors. I got all of them blue. But I want to set the color separately. How am I able to do it? The cmedian cannot be accessed by parts['cmedians'][0], parts 'cmedians' , parts 'cmedians' ...
Please ignore the data I put in.

z9ju0rcb

z9ju0rcb1#

To set the colors of median bars to separate colors, you will need to provide the colors as a list. Update the code as below...

mycolors = ['purple', 'green', 'blue'] ## Create list of colors you want to provide
parts['cmedians'].set_color(mycolors) ## Use set_color() as before

Output (with dummy data)

相关问题