[seaborn] seaborn学习笔记5-小提琴图VIOLINPLOT

文章目录

 

5 小提琴图Violinplot

(代码下载)
小提琴图允许可视化一个或多个组的数字变量的分布。它与箱形图非常接近,但可以更深入地了解密度。小提琴图特别适用于数据量巨大且无法显示个别观察结果的情况。在seaborn中使用violinplot函数绘制小提琴图,该章节主要内容有:

  1. 基础小提琴图绘制 Basic violinplot
  2. 小提琴图样式自定义 Custom seaborn violinplot
  3. 小提琴图颜色自定义 Control color of seaborn violinplot
  4. 分组小提琴图 Grouped violinplot
  5. 小提琴图组的顺序设置 Control order of groups in violinplot
  6. 显示小提琴图上的观察次数 Show number of observation on violinplot
#调用seaborn
import seaborn as sns
#调用seaborn自带数据集
df = sns.load_dataset('iris')
#显示数据集
df.head()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
 sepal_lengthsepal_widthpetal_lengthpetal_widthspecies
05.13.51.40.2setosa
14.93.01.40.2setosa
24.73.21.30.2setosa
34.63.11.50.2setosa
45.03.61.40.2setosa

1. 基础小提琴图绘制 Basic violinplot

  • 单个变量 One numerical variable only
  • 包含多个分组的单个变量 One variable and several groups
  • 多个变量 Several variables
  • 水平小提琴图 Horizontal violinplot
# 单个变量 One numerical variable only
# 如果只有一个数值变量,则最好制作直方图或密度图,但是仍然可以用小提琴图来表示
# Make boxplot for one group only
sns.violinplot( y=df["sepal_length"] );
  • 1
  • 2
  • 3
  • 4
C:\ProgramData\Anaconda3\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
  return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
  • 1
  • 2

png

# 包含多个分组的单个变量 One variable and several groups
# x为种类名,y为花萼长度
sns.violinplot( x=df["species"], y=df["sepal_length"] );
  • 1
  • 2
  • 3

png

# 多个变量 Several variables
# 单独拿出sepal_length和sepal_width绘制
sns.violinplot(data=df.iloc[:,0:2]);
  • 1
  • 2
  • 3

png

# 水平小提琴图 Horizontal violinplot
# 可以通过orient设定方向,但是交换x,y画水平小提琴图更好
# Just switch x and y
sns.violinplot( y=df["species"], x=df["sepal_length"] );
  • 1
  • 2
  • 3
  • 4

png

2. 小提琴图样式自定义 Custom seaborn violinplot

  • 线宽自定义 Change line width
  • 图像一般宽度自定义 Change width
# 线宽自定义 Change line width
sns.violinplot( x=df["species"], y=df["sepal_length"], linewidth=5);
  • 1
  • 2

png

# 图像一般宽度自定义 Change width
sns.violinplot( x=df["species"], y=df["sepal_length"], width=0.3);
  • 1
  • 2

png

3. 小提琴图颜色自定义 Control color of seaborn violinplot

  • 使用调色板 Use a color palette
  • 单种颜色 Uniform color
  • 指定每个组的颜色 Specify color of each group
  • 突出显示一个组 Highlight a group
# 使用调色板 Use a color palette
sns.violinplot( x=df["species"], y=df["sepal_length"], palette="Blues");
  • 1
  • 2

png

# 单种颜色 Uniform color
sns.violinplot( x=df["species"], y=df["sepal_length"], color="skyblue");
  • 1
  • 2

png

# 指定每个组的颜色 Specify color of each group
# Make a dictionary with one specific color per group:
my_pal = {"versicolor": "g", "setosa": "b", "virginica":"m"}
#plot it
sns.violinplot( x=df["species"], y=df["sepal_length"], palette=my_pal);
  • 1
  • 2
  • 3
  • 4
  • 5

png

# 突出显示一个组 Highlight a group
# make a vector of color: red for the interesting group, blue for others:
my_pal = {species: "r" if species == "versicolor" else "b" for species in df.species.unique()} 
# make the plot
sns.violinplot( x=df["species"], y=df["sepal_length"], palette=my_pal);
  • 1
  • 2
  • 3
  • 4
  • 5

png

4. 分组小提琴图 Grouped violinplot

# 如果您有一个变量,变量有几个组和子组,您可能需要制作一个分组的小提琴图。
df_test = sns.load_dataset('tips')
# Grouped violinplot 分组
sns.violinplot(x="day", y="total_bill", hue="smoker", data=df_test, palette="Pastel1");
  • 1
  • 2
  • 3
  • 4

png

5. 小提琴图组的顺序设置 Control order of groups in violinplot

# plot order设置顺序就行
sns.violinplot(x='species', y='sepal_length', data=df, order=[ "versicolor", "virginica", "setosa"]);
  • 1
  • 2

png

# Find the order 或者通过设置一定的规则排序
my_order = df.groupby(by=["species"])["sepal_length"].median().iloc[::-1].index
# Give it to the violinplot
sns.violinplot(x='species', y='sepal_length', data=df, order=my_order);
  • 1
  • 2
  • 3
  • 4

png

6. 显示小提琴图上的观察次数 Show number of observation on violinplot

# Basic violinplot 基础小提琴图像绘制
ax = sns.violinplot(x="species", y="sepal_length", data=df)
 
# Calculate number of obs per group & median to position labels 计算各个样本数量
medians = df.groupby(['species'])['sepal_length'].median().values
nobs = df['species'].value_counts().values
nobs = [str(x) for x in nobs.tolist()]
nobs = ["n: " + i for i in nobs]
 
# Add it to the plot 加入图像
pos = range(len(nobs))
for tick,label in zip(pos,ax.get_xticklabels()):
   ax.text(pos[tick], medians[tick] + 0.03, nobs[tick], horizontalalignment='center', size='x-small', color='w', weight='semibold');
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

png

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于使用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、付费专栏及课程。

余额充值