繁体   English   中英

如何获得 seaborn 分布(和 plot 对应的行)的最大 x 值?

[英]How to get the max x value of a seaborn distribution (and plot the corresponding line)?

我正在做一个关于我的 Spotify 播放列表的项目,其中 output 是 6 个分布图,每个图有 3 条线。 是这样的:

在此处输入图像描述

我希望每条曲线到 plot 一条垂直线到达每条曲线的顶部,并将 x 值放在 x 轴上。 是这样的:

在此处输入图像描述

我在这里找到了解决方案。 但是在尝试了很多工作之后,这似乎对我不起作用,因为我使用 sub plot。如果你想使用,我已经完成了一个更简单/可用的代码。

from pylab import *
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

input1 = np.random.normal(loc=0.2, scale=1.0, size=25)
output1 = np.random.normal(loc=0.3, scale=1.0, size=25)

input2 = np.random.normal(loc=0.1, scale=1.0, size=25)
output2 = np.random.normal(loc=0.15, scale=1.0, size=25)
inputs = [input1 , input2]
outputs = [output1 , output2]

my_alpha = 0.03
my_linewidth = 0.7
for i in range(len(inputs)):
    fig = subplot(1,2,i+1)
    ax1 = sns.kdeplot(inputs[i], shade=True, alpha=my_alpha, linewidth=my_linewidth, label = 'Input Playlist', color = '#2cc758')
    ax2 = sns.kdeplot(outputs[i], shade=True, alpha=my_alpha, linewidth=my_linewidth, label = 'Recommandations Made', color = '#dbb818')

myLegend = plt.legend(loc='lower left', bbox_to_anchor=(-1.2,1.05), ncol=3) #legend location is set from the last ploted graph
myLegend.set_title("Tracks Set")
plt.setp(myLegend.get_title())

plt.show()

如果您有一些想法,我将很高兴阅读您的文章。
感谢社区

为了使其与最新的 seaborn 版本一起使用,需要fill=False来获取一行。 然后,该线可用于fill_between并提取最高点。 当同一个子图上有多个 kdeplot 时, ax.lines[-1]给出最后添加的曲线。

使用没有计数器的for循环有助于使代码更易于维护。

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

input1 = np.random.normal(loc=0.2, scale=1.0, size=25)
output1 = np.random.normal(loc=0.3, scale=1.0, size=25)

input2 = np.random.normal(loc=0.1, scale=1.0, size=25)
output2 = np.random.normal(loc=0.15, scale=1.0, size=25)
inputs = [input1, input2]
outputs = [output1, output2]

fig, axs = plt.subplots(ncols=len(inputs), figsize=(15, 5))
for ax, input_i, output_i in zip(axs, inputs, outputs):
    for data, label, color in zip([input_i, output_i],
                                  ['Input Playlist', 'Recommandations Made'],
                                  ['#2cc758', '#dbb818']):
        sns.kdeplot(data, fill=False, linewidth=0.7, label=label, color=color, ax=ax)
        xs, ys = ax.lines[-1].get_data()
        ax.fill_between(xs, ys, color=color, alpha=0.05)
        mode_idx = np.argmax(ys)
        ax.vlines(xs[mode_idx], 0, ys[mode_idx], ls='--', color=color)
        ax.text(xs[mode_idx], -0.1, f'{xs[mode_idx]:.2f}', color=color, ha='center', transform=ax.get_xaxis_transform())

myLegend = axs[0].legend(loc='lower left', bbox_to_anchor=(0, 1.02), ncol=3)
myLegend.set_title("Tracks Set")
plt.tight_layout()
plt.show()

sns.kdeplot 指示模式

暂无
暂无

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

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