原文:Python数据处理从零开始----第四章(可视化)(16)一文解决小提琴图violin plotwww.jianshu.com
Python数据处理从零开始----第四章(可视化)(16)一文解决小提琴图violin plot
(1)输入数据所使用的是经典的iris数据, 包括有sepal_length, sepal_width, petal_length,petal_width和 species五个变量,其中前四个为数字变量,最后一个为分类变量
import seaborn as sns df = sns.load_dataset('iris') df.head() Out[25]: sepal_length sepal_width petal_length petal_width species 0 5.1 3.5 1.4 0.2 setosa 1 4.9 3.0 1.4 0.2 setosa 2 4.7 3.2 1.3 0.2 setosa 3 4.6 3.1 1.5 0.2 setosa 4 5.0 3.6 1.4 0.2 setosa
(2)绘制基础图形
# In[*] # Make boxplot for one group only sns.violinplot( y=df["sepal_length"] ) #sns.plt.show()
这里是小提琴图里最基础的图片,目的是为了展示sepal_length数据的分布
(3)绘制经典的小提琴图:One variable and several groups
# library & dataset import seaborn as sns df = sns.load_dataset('iris') # plot sns.violinplot( x=df["species"], y=df["sepal_length"] ) #sns.plt.show()
这里是小提琴图里最经典的图片,目的是展示不同species的观察值在sepal_length的分布。我们可以看出virginica的平均sepal_length最高,而setosa的平均sepal_length最低。
(4)绘制经典的小提琴图:several variables
# In[*] # library & dataset import seaborn as sns df = sns.load_dataset('iris') # plot sns.violinplot(data=df.ix[:,0:2]) #sns.plt.show()
(5)绘制横放的小提琴图
# library & dataset import seaborn as sns df = sns.load_dataset('iris') # Just switch x and y sns.violinplot( y=df["species"], x=df["sepal_length"] ) #sns.plt.show()
(6) change linewidth修改线条宽度
# In[*] import seaborn as sns df = sns.load_dataset('iris') # Change line width sns.violinplot( x=df["species"], y=df["sepal_length"], linewidth=5) #sns.plt.show()
(7) Change width修改图形宽度
# In[*] # Change width sns.violinplot( x=df["species"], y=df["sepal_length"], width=1) #sns.plt.show()
(8) 使用colorpalette设置小提琴图颜色
# library & dataset import seaborn as sns df = sns.load_dataset('iris') # Use a color palette sns.violinplot( x=df["species"], y=df["sepal_length"], palette="Blues")
(9) 使用某个特定颜色设置小提琴图颜色
import seaborn as sns df = sns.load_dataset('iris') # plot sns.violinplot( x=df["species"], y=df["sepal_length"], color="skyblue")
(10) 指定不同分组使用不同颜色
import seaborn as sns df = sns.load_dataset('iris') # 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)
(11) 突出某个分组的颜色
import seaborn as sns df = sns.load_dataset('iris') # 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)
(12) 绘制分组小提琴图当我们同时有一个numerical variable,许多个 groups, 还有一个subgroups, 我们这个时候就需要分组小提琴图,也就是 grouped violinplot。场景示例:我们想知道男女两类患者,在青少年、中年、老年这三个年龄阶段,在肺癌发病率的分布
# library & dataset import seaborn as sns df = sns.load_dataset('tips') # Grouped violinplot sns.violinplot(x="day", y="total_bill", hue="smoker", data=df, palette="Pastel1") #sns.plt.show()
我们可以看出在Fri上,吸烟者和不吸烟者total_bill的差别很大。而在Thur上,吸烟者和不吸烟者total_bill的差别很小。
(13) 设置小提琴图分组的顺序这里我们设置的是 "versicolor", "virginica", "setosa",也就是说先展示versicolor组的数据,最后展示setosa组的数据。
import seaborn as sns df = sns.load_dataset('iris') # plot sns.violinplot(x='species', y='sepal_length', data=df, order=[ "versicolor", "virginica", "setosa"])
(14) 设置小提琴图分组的顺序(根据中位数大小)
import seaborn as sns df = sns.load_dataset('iris') # 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)
(15) 在小提琴图上周展示每个分组的观察值总数。
import seaborn as sns, numpy as np df = sns.load_dataset("iris") # 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') #sns.plt.show()
我们可以看出setosa组共计有50个观察值observation。而versicolor和virginica组也有50个观察值。