【问题标题】:python violin plot regular axispython小提琴图规则轴
【发布时间】:2021-03-07 17:00:24
【问题描述】:

我想绘制分箱数据的小提琴图,但同时能够绘制模型预测并可视化模型描述各个数据分布的主要部分的程度。我想我的问题是,小提琴图之后的 x 轴不像带有数字的常规轴,而更像是偶然碰巧是数字的字符串值。也许不是一个很好的描述,但在示例中,我想要一个“正常”的函数,例如f(x) = 2*x**2,在 x=1、x=5.2、x=18.3 和 x=27 时,我希望背景中有小提琴。

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

np.random.seed(10)
collectn_1 = np.random.normal(1, 2, 200)
collectn_2 = np.random.normal(802, 30, 200)
collectn_3 = np.random.normal(90, 20, 200)
collectn_4 = np.random.normal(70, 25, 200)

ys = [collectn_1, collectn_2, collectn_3, collectn_4]
xs = [1, 5.2, 18.3, 27]

sns.violinplot(x=xs, y=ys)

xx = np.arange(0, 30, 10)
plt.plot(xx, 2*xx**2)

plt.show()

不知何故,这段代码实际上并没有绘制小提琴,而只是绘制小节,这只是这个例子中的一个问题,而不是原始代码中的问题。在我的真实代码中,我希望两边都有不同的“半小提琴”,因此我使用sns.violinplot(x="..", y="..", hue="..", data=.., split=True)

【问题讨论】:

  • 在尝试使用 Seaborn 0.11 运行您的代码时,violinplot 似乎不接受ys 的格式。它需要'long' 格式,所以使用ys = np.concatenate([collectn_1, collectn_2, collectn_3, collectn_4]); xs = np.repeat([1, 5.2, 18.3, 27], [len(collectn_1), len(collectn_2), len(collectn_3), len(collectn_4)]) 它可以工作。奇怪的缩放来自scale= 参数,该参数默认为'area',并缩放最后 3 把小提琴的宽度,使其面积等于第 1 把小提琴(非常短)。设置scale='width' 可以让小提琴看起来更标准。
  • 谢谢,这种行为很大程度上取决于使用的 seaborn 版本。

标签: python seaborn violin-plot


【解决方案1】:

我认为seaborn 很难做到这一点,因为它没有提供一种简单的方法来操纵它创建的艺术家,特别是如果在同一个轴上绘制了其他东西。 Matplotlib 的violinplot 允许设置小提琴的位置,但不提供仅绘制一半小提琴的选项。因此,我建议使用statsmodels.graphics.boxplots.violinplot,两者兼而有之。

from statsmodels.graphics.boxplots import violinplot

df = sns.load_dataset('tips')
x_col = 'day'
y_col = 'total_bill'
hue_col = 'smoker'

xs = [1, 5.2, 18.3, 27]
xx = np.arange(0, 30, 1)
yy = 0.1*xx**2
cs = ['C0','C1']

fig, ax = plt.subplots()

ax.plot(xx,yy)


for (_,gr0),side,c in zip(df.groupby(hue_col),['left','right'],cs):
    print(side)
    data = [gr1 for (_,gr1) in gr0.groupby(x_col)[y_col]]
    violinplot(ax=ax, data=data, positions=xs, side=side, show_boxplot=False, plot_opts=dict(violin_fc=c))

# violinplot above messes up which ticks are shown, the line below restores a sensible tick locator
ax.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator())

【讨论】:

  • 正是我想要的。非常感谢!有趣的是有多少工具可以绘制小提琴:)
猜你喜欢
  • 2017-09-03
  • 2016-08-20
  • 2017-08-30
  • 2021-06-15
  • 2017-08-11
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 2021-08-27
相关资源
最近更新 更多