Changing the color of matplotlib’s violin plots

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)