简体   繁体   中英

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. 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.
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

Using seaborn , you need to transform your data in a dataframe. The split= argument is to be used with hue -nesting, which can only be used if you already have an x= argument. Therefore you need to provide columns for both x (should be the same value for both datasets) and hue (coded depending on the dataset):

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

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'})

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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