pythonmatplotlib绘图小提琴_matplotlib-为小提琴图制作标签

I usually make labels for bars in the following manner using parameter 'label' in the method 'bar'.

axes[0].bar(x, y, bar_width, label='abc')

axes[0].legend()

Now I'd like to plot violin plots and make label for each collection as follows, but it doesn't work since 'violinplot' doesn't have the parameter 'label'.

axes[0].violinplot(data1, label='abc1')

axes[1].violinplot(data2, label='abc2')

Can anyone help me out to make a label for each collection?

解决方案

As it was mentioned in comment, some plots in matplotlib don't support legends. Documentation still provides a simple way to add custom legends for them: http://matplotlib.org/users/legend_guide.html#proxy-legend-handles

Main idea : add 'fake' objects, which can be not shown in the plot, then use it to form a handles list for legend method.

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()

好的,关于使用Python的Seaborn库绘制小提琴,有一些需要注意的地方。 首先,要确保已经安装了Seaborn库。可以使用以下命令安装: ``` pip install seaborn ``` 其次,需要导入Seaborn库和Matplotlib库: ```python import seaborn as sns import matplotlib.pyplot as plt ``` 接下来,我们需要准备数据。小提琴通常用于显示数值型变量的分布情况,最常见的是显示不同类别或组之间的比较。因此,我们需要将数据按照类别或组分组。 例如,我们有一个数据集,其中包含了不同城市的温度数据。我们可以按照城市将数据分组,并将每个城市的温度数据存储在一个列表中。 ```python data = { 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix'], 'Temperature': [ [68, 73, 77, 80, 83, 87, 88, 88, 85, 80, 74, 68], [55, 60, 62, 64, 68, 72, 75, 76, 74, 70, 62, 55], [28, 32, 40, 52, 63, 72, 77, 75, 68, 56, 42, 30], [49, 53, 60, 69, 77, 83, 87, 87, 81, 71, 60, 50], [65, 68, 74, 81, 89, 97, 100, 99, 93, 83, 72, 63] ] } ``` 接下来,我们可以使用Seaborn库的violinplot函数来绘制小提琴: ```python sns.violinplot(x='City', y='Temperature', data=data) plt.show() ``` 这将会生成一个小提琴,其中x轴表示城市名称,y轴表示温度值。 然而,有时候我们可能会遇到一些小坑。比如,当我们使用Seaborn库的violinplot函数绘制小提琴时,如果数据集中有缺失值,会导致程序崩溃。因此,我们需要在绘图之前先处理好数据,确保不存在缺失值。 此外,如果数据集中存在异常值,也可能会导致小提琴绘制不准确。因此,在绘制小提琴之前,我们需要对数据进行合理的处理和清洗。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值