在 python 水平移动小提琴图

shifting violin plot horizontally in python

我有 8 个不同的 arryas,我想使用小提琴图来比较分布,这就是我绘制的方式:

plt.violinplot(alpha_g159)
plt.violinplot(alpha_g108)
plt.violinplot(alpha_g141)
plt.violinplot(alpha_g110)
plt.violinplot(alpha_g115)
plt.violinplot(alpha_g132)
plt.violinplot(alpha_g105)
plt.violinplot(alpha_g126)

我有这个情节:

实际上我想做的是水平移动每个图(沿 x 轴),这样它们就不会重叠,然后在 x 轴上添加每个图的标签。

谁能指导我如何做到这一点?例如,我尝试添加 alpha_108+x0x0=2,但它只是垂直移动。

您可以通过将数据放入列表来实现此目的。 Matplotlib 并排绘制各个图。

import matplotlib.pyplot as plt
import numpy as np

# put your data in a list like this:
# data = [alpha_g159, alpha_g108, alpha_g141, alpha_g110, alpha_g115, alpha_g132, alpha_g105, alpha_g126]
# as I do not have your data I created some test data
data = [sorted(np.random.normal(0, std, 100)) for std in range(1, 9)]
plt.violinplot(data)

labels = ["alpha_g159", "alpha_g108", "alpha_g141", "alpha_g110", "alpha_g115", "alpha_g132", "alpha_g105", "alpha_g126"]
# add the labels (rotated by 45 degrees so that they do not overlap)
plt.xticks(range(1, 9), labels, rotation=45)

# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.3)

plt.show()

resulting plot