我通常使用“bar”方法中的参数“label”按以下方式为条形图制作标签。
axes[0].bar(x, y, bar_width, label='abc')
axes[0].legend()
现在我想绘制小提琴图并为每个集合制作标签,如下所示,但它不起作用,因为“violinplot”没有参数“label”。
axes[0].violinplot(data1, label='abc1')
axes[1].violinplot(data2, label='abc2')
有人可以帮我为每个系列制作一个标签吗?
这是我针对多个小提琴图的解决方案。请注意,它从给定小提琴图的第一个阴影区域获取补丁颜色——如果有多种颜色,则可以将其更改为执行其他操作,或者您可以使用
violin["cbars"].get_color().flatten()
获取垂直条的颜色。
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
labels = []
def add_label(violin, label):
color = violin["bodies"][0].get_facecolor().flatten()
labels.append((mpatches.Patch(color=color), label))
positions = np.arange(3,13,3)
data = np.random.randn(1000, len(positions))
add_label(plt.violinplot(data, positions), "Flat")
positions = np.arange(1, 10, 2)
data = np.random.randn(1000, len(positions)) + positions
add_label(plt.violinplot(data, positions), "Linear")
positions = np.arange(2, 11, 1)
data = np.random.randn(1000, len(positions)) + positions ** 2 / 4
add_label(plt.violinplot(data, positions), "Quadratic")
plt.legend(*zip(*labels), loc=2)
正如评论中提到的,matplotlib 中的某些绘图不支持图例。文档仍然提供了一种简单的方法来为其添加自定义图例:http://matplotlib.org/users/legend_guide.html#proxy-legend-handles
主要思想:添加无法在图中显示的“假”对象,然后用它来形成图例方法的句柄列表。
import random
import numpy as np
import matplotlib.pyplot as pl
import matplotlib.patches as mpatches
from itertools import repeat
red_patch = mpatches.Patch(color='red')
# 'fake' invisible object
pos = [1, 2, 4, 5, 7, 8]
label = ['plot 1','plot2','ghi','jkl','mno','pqr']
data = [np.random.normal(size=100) for i in pos]
fake_handles = repeat(red_patch, len(pos))
pl.figure()
ax = pl.subplot(111)
pl.violinplot(data, pos, vert=False)
ax.legend(fake_handles, label)
pl.show()
有一个比 @Ian Hincks 代码更简单的解决方案,无需使用
mpatches
import matplotlib.pyplot as plt
import numpy as np
positions = np.arange(3,13,3)
data = np.random.randn(1000, len(positions))
vp1 = plt.violinplot(data, positions)
positions = np.arange(1, 10, 2)
data = np.random.randn(1000, len(positions)) + positions
vp2 = plt.violinplot(data, positions)
positions = np.arange(2, 11, 1)
data = np.random.randn(1000, len(positions)) + positions ** 2 / 4
vp3 = plt.violinplot(data, positions)
plt.legend([vp1['bodies'][0],vp2['bodies'][0], vp3['bodies'][0]], ['flat', 'linear', 'quadratic'], loc=2)[enter image description here][1]
要使用线条代替主体,请将
vp1['bodies'][0]
替换为 vp1['cbars']
演示:带有标签的小提琴图
编辑:抱歉,我现在看到您想添加图例,而不是轴标签...
您可以手动设置刻度位置,然后覆盖其标签:
import numpy as np
import matplotlib.pyplot as pl
pos = [1, 2, 4, 5, 7, 8]
label = ['abc','def','ghi','jkl','mno','pqr']
data = [np.random.normal(size=100) for i in pos]
pl.figure()
ax = pl.subplot(111)
pl.violinplot(data, pos, vert=False)
ax.set_yticks(pos)
ax.set_yticklabels(label)
更精简、清晰的解决方案可以是:
plt.style.use('seaborn')
import matplotlib.pyplot as plt
labels = ['df=9' , 'df=99', 'df=999', 'df=9999', 'N($\mu=0$, $\sigma=2)$']
colors = ['orange', 'lightblue', 'lightgreen', 'yellow', 'green']
def make_violinplot(x, labels, colors):
parts = plt.violinplot(x, showmeans=True, showmedians=True)
for body, color in zip(parts['bodies'],colors):
body.set_facecolor(color)
parts['cmeans'].set_color('red')
parts['cmedians'].set_color('blue')
plt.legend(label[enter image description here][1]s, loc='upper left')
plt.xticks(np.arange(1, len(labels)+1), labels)
plt.title("probability density plots t- vs normal distribution")
plt.rcParams["figure.figsize"] = [8,8]
return
make_violinplot(t_dists, labels, colors)
matplotlib 官方文档有一个关于自定义小提琴图的指南,可能对您有用:https://matplotlib.org/stable/gallery/statistics/customized_violin.html