【问题标题】:getting only the last plot只得到最后一个情节
【发布时间】:2021-04-24 04:16:23
【问题描述】:

当通过下面的代码进行绘图时,我得到 c、d、e 绘图,但我只得到 plt.plot 的最后一个绘图

def normalize(x):
    return (x - x.min(0)) / x.ptp(0)
c=sns.distplot(mk[0]['mass'], hist=True, label='p', rug=True)
d=sns.distplot(mk[1]['mass'], hist=True, label='q', rug=True)
e=sns.distplot(mk[2]['mass'], hist=True, label='r', rug=True)
datadist=[c,d,e]
xd=dict()
yd2=dict()
for i in datadist:
    line = i.get_lines()[0]
    xd[i] = line.get_xdata()
    yd = line.get_ydata()   
    yd2[i] = normalize(yd)
plt.plot(xd[c], yd2[c],color='black')
plt.plot(xd[d], yd2[d],color='yellow')
plt.plot(xd[e], yd2[e],color='green')

【问题讨论】:

  • 我已经展示了规范化函数是如何定义的。我想在一个图中绘制最后 3 行图。@JohanC​​pan>
  • 是的,在单独的图中我想显示 plt.plot(xd[c], yd2[c],color='black') plt.plot(xd[d], yd2[d ],color='yellow') plt.plot(xd[e], yd2[e],color='green') 我不需要 c,d,e 的图 @JohanC​​pan>

标签: matplotlib seaborn


【解决方案1】:

sns.distplot() 返回绘制直方图的ax(子图)。 3个都画在同一个子图上,所以3次返回值是一样的。

数组lines = ax1.get_lines() 正好包含 3 个元素:每个 kde 曲线一个,因此您可以按如下方式提取它们:

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

def normalize(x):
    return (x - x.min(0)) / x.ptp(0)

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14, 4))
sns.distplot(np.random.randn(30) + 10, hist=True, label='p', rug=True, ax=ax1, color='black')
sns.distplot(np.random.randn(30) + 15, hist=True, label='q', rug=True, ax=ax1, color='gold')
sns.distplot(np.random.randn(30) + 20, hist=True, label='r', rug=True, ax=ax1, color='green')

for line in ax1.get_lines():
    ax2.plot(line.get_xdata(), normalize(line.get_ydata()), color=line.get_color())
plt.show()

现在,如果您只想要 kde 曲线并“标准化”它们,您可以使用 scipy.stats import gaussian_kde

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

def normalize(x):
    return (x - x.min(0)) / x.ptp(0)

fig, ax = plt.subplots(figsize=(12, 4))

mk0mass = np.random.randn(30) + 10
mk1mass = np.random.randn(30) + 15
mk2mass = np.random.randn(30) + 20
all_mkmass = [mk0mass, mk1mass, mk2mass]
x = np.linspace(min([mki.min() for mki in all_mkmass]) - 2,
                max([mki.max() for mki in all_mkmass]) + 2, 1000)
for mki, color in zip(all_mkmass, ['black', 'gold', 'green']):
    kde = gaussian_kde(mki)
    yd = normalize(kde(x))
    ax.plot(x, yd, color=color)
    ax.fill_between(x, 0, yd, color=color, alpha=0.3)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    相关资源
    最近更新 更多