Tommy95
Tommy95

Reputation: 193

Change the color of the individual max and mean line in a violin plot using matplotlib

So basically I want to change the color of the mean, min and max lines for each violin in my plot.

I know that I can change the color of all violins in my plot by using the dictionary:

violin_parts = ax_lst[0].violinplot(tmp_list, showmedians=True, quantiles=[[0.99], [0.99], [0.99],[0.99]])
for partname in ('cbars','cmins','cmaxes','cmedians','cquantiles'):
        vp = violin_parts[partname]
        vp.set_edgecolor("#3498db")
        vp.set_linewidth(1.6)
        vp.set_alpha(1) 

The problem is that with this approach I can't edit the individual line for each violin and I can't seem to find a workaround for it. For some reason only the body itself is accessible as an iterator for all violins.

Upvotes: 0

Views: 2663

Answers (1)

r-beginners
r-beginners

Reputation: 35135

You can get a collection of violin plots and set it to any collection of violins with set_color. The color you get is a list of one color, so you can convert it to a list containing any color you want to deal with.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollection

# create test data
np.random.seed(20210903)
data = [sorted(np.random.normal(0, std, 100)) for std in range(1, 5)]

fig, ax = plt.subplots(figsize=(8, 4))

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

cmax_colors = parts['cmaxes'].get_color()
colors = [cmax_colors[0],'red',cmax_colors[0],cmax_colors[0]]
parts['cmaxes'].set_color(colors)

cmin_colors = parts['cmins'].get_color()
colors = [cmin_colors[0],'red',cmin_colors[0],cmin_colors[0]]
parts['cmins'].set_color(colors)

cmean_colors = parts['cmeans'].get_color()
colors = [cmean_colors[0],'red',cmean_colors[0],cmean_colors[0]]
parts['cmeans'].set_color(colors)

cbar_colors = parts['cbars'].get_color()
colors = [cbar_colors[0],'red',cbar_colors[0],cbar_colors[0]]
parts['cbars'].set_color(colors)

plt.show()

enter image description here

Upvotes: 2

Related Questions