[英]Using Seaborn to connect corresponding x and y events on a scatter plot with a line
[英]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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.