改变matplotlib的小提琴图的颜色

33

有没有办法在matplotlib中改变violin图的颜色?

默认颜色是这种“棕褐色”,不太糟糕,但我想着色例如前3个小提琴,以突出显示它们。我在文档中没有找到任何参数。有什么想法或技巧可以使小提琴的颜色不同吗?

enter image description here


你能否提出一个功能请求来添加这个功能呢?小提琴图是1.4中的一个新功能,但(显然)仍需要一些改进。 - tacaswell
3个回答

50

matplotlib.pyplot.violinplot()返回一个字典,将每个小提琴图的组成部分映射到相应创建的集合实例列表。该字典有以下键:

  • bodies: 包含每个小提琴填充区域的matplotlib.collections.PolyCollection实例的列表。
  • [...其他内容...]

PolyCollections的方法包括:

因此,似乎您可以遍历结果的body列表并修改每个的facecolor:

violin_parts = plt.violinplot(...)

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

虽然很奇怪,但是您无法像常见的绘图类型一样在创建时设置它。我猜这可能是因为该操作会创建许多位(前述的PolyCollection以及另外5个LineCollections),添加其他参数可能会产生歧义。


2
谢谢,for patch, color in zip(vplot['bodies'], colors): patch.set_color(color) 已经完成了工作! - user2489252
1
或者使用 plt.setp 进行简写,例如 plt.setp(violin_parts['bodies'], facecolor='red', edgecolor='black') - Syrtis Major
2
只是想说,violin_parts.keys() 将列出您可以调整的所有不同部分。例如:dict_keys(['bodies', 'cmaxes', 'cmins', 'cbars', 'cmedians'])。 然后,dir(violin_parts['cbars']) 将列出您可以设置的属性。例如:violin_parts['cbars'].set_linewidth(1) - blaylockbk

17
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


1
由于您不知道是否启用了等等,因此可以使用for partname in violin_parts循环遍历所有可用部件。但是,由于“bodies”部分本身就是一个列表,因此您必须跳过它(使用if partname == 'bodies': continue)并手动处理它。(基于我从@Nick T答案的评论中学到的内容。) - F1iX

3
假设你有 3 个向量:data1、data2、data3;并且你已经在一个图中绘制了你的 matplotlib 小提琴图;那么,为了设置每个子小提琴图的中位线颜色正文颜色,你可以使用以下代码:
colors = ['Blue', 'Green', 'Purple']

# Set the color of the violin patches
for pc, color in zip(plots['bodies'], colors):
    pc.set_facecolor(color)

# Set the color of the median lines
plots['cmedians'].set_colors(colors)

完整示例:

# Set up the figure and axis
fig, ax = plt.subplots(1, 1)

# Create a list of the data to be plotted
data = [data1, data2, data3]

# Set the colors for the violins based on the category
colors = ['Blue', 'Green', 'Purple']

# Create the violin plot
plots = ax.violinplot(data, vert=False, showmedians=True, showextrema=False, widths=1)

# Set the color of the violin patches
for pc, color in zip(plots['bodies'], colors):
    pc.set_facecolor(color)

# Set the color of the median lines
plots['cmedians'].set_colors(colors)

# Set the labels
ax1.set_yticks([1, 2, 3], labels=['category1', 'category2', 'category3'])

ax1.invert_yaxis() # ranking from top to bottom: invert yaxis

plt.show()

Example for matplotlib violin plots with different colors


谢谢!这实际上是唯一完整的答案(展示如何改变所有元素的颜色,而不仅仅是小提琴的身体)。添加一个图形可以大大提高其可见性。 - Roger Vadim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接