简体   繁体   English

如何使用 Matplotlib 在 python 中创建非对称小提琴图

[英]How to create asymmetric violin plot in python using Matplotlib

I have these two sample datasets:我有这两个示例数据集:

data = np.exp ( np.random.randn(N) ) 
data[data>threshold] = threshold + np.random.randn(sum(data>threshold))*0.2
data_1 = data
data_2 = np.random.randn(N)

And I would like to know how to create an asymmetric violin plot using Matplotlib plt.violinplot() in which both datasets plotted in two sides of the same axis.我想知道如何使用 Matplotlib plt.violinplot()创建一个不对称的小提琴图,其中两个数据集都绘制在同一轴的两侧。 Unfortunately I could not find the proper options for this function as it is available for statsmodels.graphics.boxplots.violinplot(side=) or for seaborn library.不幸的是,我找不到此功能的正确选项,因为它可用于statsmodels.graphics.boxplots.violinplot(side=)seaborn库。
This is my code for separated violin plots:这是我分离小提琴图的代码:

import numpy as np
import matplotlib.pyplot as plt 

N = 10000
threshold = 5 

data = np.exp ( np.random.randn(N) ) 
data[data>threshold] = threshold + np.random.randn(sum(data>threshold))*0.2

data_1 = data
data_2 = np.random.randn(N)
plt.figure(figsize = (15,5))
plt.subplot(1,2,1)
plt.violinplot(data_1)
plt.title('Violin Plot For Dataset 1')

plt.subplot(1,2,2)[enter image description here][1]
plt.violinplot(data_2)
plt.title('Violin Plot For Dataset 2');

The result is attached.结果附后。 [1]: https://i.stack.imgur.com/hx0Ha.png [1]: https : //i.stack.imgur.com/hx0Ha.png

Using seaborn , you need to transform your data in a dataframe.使用seaborn ,您需要在数据seaborn转换数据。 The split= argument is to be used with hue -nesting, which can only be used if you already have an x= argument.所述split=参数是与被用于hue -nesting,如果已经有一个其中仅可用于x=参数。 Therefore you need to provide columns for both x (should be the same value for both datasets) and hue (coded depending on the dataset):因此,您需要为x (两个数据集的值应该相同)和hue (根据数据集编码)提供列:

N=100
data_1 = np.random.normal(loc=1, size=N)
data_2 = np.random.normal(loc=2, size=N)

data = pd.DataFrame({'data_1':data_1, 'data_2':data_2})
data = data.melt()
data['dummy'] = 0

sns.violinplot(data=data, y='value', split=True, hue='variable', x='dummy')

在此处输入图片说明

Using statsmodels.graphics.boxplots.violinplot requires two calls, one for each dataset使用statsmodels.graphics.boxplots.violinplot需要两次调用,每个数据集调用一次

from statsmodels.graphics.boxplots import violinplot
fig, ax = plt.subplots()
violinplot([data_1], positions=[0], show_boxplot=False, side='left', ax=ax, plot_opts={'violin_fc':'C0'})
violinplot([data_2], positions=[0], show_boxplot=False, side='right', ax=ax, plot_opts={'violin_fc':'C1'})

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM