Reputation: 355
I am preparing violin plots with the data I have.
What I want to do is to give a distinct color, like a rainbow colormap, to my plots in the violin plot. I have something running with the exact same color, but I want to introduce some variation.
vp1 = violinplot(y1, x1, points=20, widths=0.9, showmeans=True, showextrema=False, showmedians=False)
for pc in vp1['bodies']:
pc.set_facecolor('red')
pc.set_edgecolor('black')
vp1['cmeans'].set_color('black')
How do I go about this?
Upvotes: 1
Views: 751
Reputation: 27557
You can use a list of colors:
vp1 = violinplot(y1, x1, points=20, widths=0.9, showmeans=True, showextrema=False, showmedians=False)
colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violat"]
len_colors = len(colors)
i = 0
for pc in vp1['bodies']:
pc.set_facecolor(colors[i])
pc.set_edgecolor('black')
i += 1
if i == len_colors:
i = 0
vp1['cmeans'].set_color('black')
Explanation:
i = 0
sets the index for the colors
to 0
, and after each use of a color, increment the variable by 1
, so that the next color will be the next color in the list.
If i
got incremented to the point where it's equal to the length of colors
, set its value back to 0
.
If you want each color to be completely random and different, you can use the random()
method from the built-in random
module:
from random import random
# Your code
vp1 = violinplot(y1, x1, points=20, widths=0.9, showmeans=True, showextrema=False, showmedians=False)
for pc in vp1['bodies']:
pc.set_facecolor((random(), random(), random()))
pc.set_edgecolor('black')
vp1['cmeans'].set_color('black')
Upvotes: 1
Reputation: 854
import random
def randomColor():
r = lambda: random.randint(0,255)
color = '#{:02x}{:02x}{:02x}'.format(r(), r(), r())
return color
vp1 = violinplot(y1, x1, points=20, widths=0.9, showmeans=True, showextrema=False, showmedians=False)
for pc in vp1['bodies']:
pc.set_facecolor(randomColor())
pc.set_edgecolor('black')
vp1['cmeans'].set_color('black')
You can use this if you have 100s of columns. The function randomColor()
generates a random hex
value and gives a random color every iteration.
Upvotes: 1