Search code examples
matplotlibplotdata-sciencevisualizationviolin-plot

How to change the median line color for each violin plot in one ax, using matplotlib?


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: enter image description here

However, this is the output that I want: enter image description here

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.


Solution

  • 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)

    enter image description here