Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the color of matplotlib's violin plots

People also ask

How do you change the color of a violin plot?

Change violin plot fill colors It is also possible to change manually violin plot colors using the functions : scale_fill_manual() : to use custom colors. scale_fill_brewer() : to use color palettes from RColorBrewer package. scale_fill_grey() : to use grey color palettes.

What does a violin plot show?

A violin plot depicts distributions of numeric data for one or more groups using density curves. The width of each curve corresponds with the approximate frequency of data points in each region. Densities are frequently accompanied by an overlaid chart type, such as box plot, to provide additional information.


matplotlib.pyplot.violinplot() says it returns:

A dictionary mapping each component of the violinplot to a list of the corresponding collection instances created. The dictionary has the following keys:

  • bodies: A list of the matplotlib.collections.PolyCollection instances containing the filled area of each violin.
  • [...among others...]

Methods of PolyCollections include:

  • set_color(c) which sets both the facecolor and edgecolor,
  • set_facecolor(c) and
  • set_edgecolor(c) all of which take a "matplotlib color arg or sequence of rgba tuples"

So, it looks like you could just loop through the result's body list and modify the facecolor of each:

violin_parts = plt.violinplot(...)

for pc in violin_parts['bodies']:
    pc.set_facecolor('red')
    pc.set_edgecolor('black')

It is a bit strange though that you can't set this when creating it like the common plot types. I'd guess it's probably because the operation creates so many bits (the aforementioned PolyCollection along with 5 other LineCollections), that additional arguments would be ambiguous.


import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

rrred = '#ff2222'
bluuu = '#2222ff'
x = np.arange(2, 25)
y = np.array([xi * np.random.uniform(0, 1, 10**3) for xi in x]).T

# Create violin plot objects:
fig, ax = plt.subplots(1, 1, figsize = (8,8))
violin_parts = ax.violinplot(y, x, widths = 0.9, showmeans = True, showextrema = True, showmedians = True)

# Make all the violin statistics marks red:
for partname in ('cbars','cmins','cmaxes','cmeans','cmedians'):
    vp = violin_parts[partname]
    vp.set_edgecolor(rrred)
    vp.set_linewidth(1)

# Make the violin body blue with a red border:
for vp in violin_parts['bodies']:
    vp.set_facecolor(bluuu)
    vp.set_edgecolor(rrred)
    vp.set_linewidth(1)
    vp.set_alpha(0.5)

enter image description here