简体   繁体   English

无法显示seaborn distplot

[英]Can't display the seaborn distplot

I am trying to make a histogram and a density plot using the seaborn module of Python , and on the plot I am also trying to draw a vertical line at the mode.我正在尝试使用Pythonseaborn模块制作直方图和密度图,并且在绘图上我还尝试在模式处绘制一条垂直线。 However, the resulting plot does not display any histogram and/or density curve.但是,生成的图不会显示任何直方图和/或密度曲线。 My code is below:我的代码如下:

# a function to compute mode of the histograms shown in Figures `2` and `3` in the paper.
def compute_mode(layer_list):
    
    ax = sns.distplot(layer_list, hist=False, kde=True, kde_kws={'linewidth': 2})
    x = ax.lines[0].get_xdata()
    y = ax.lines[0].get_ydata()
    mode_idx = y.argmax()
    mode_x = x[mode_idx]
    plt.close()
        
    return mode_x

# function to plot the histogram of the layer lists.
def make_density(layer_list, color):

    
    # Plot formatting
    plt.xlabel('Median Stn. MC-Loss')
    plt.ylabel('Density')

    
    # Draw the histogram and fit a density plot.
    sns.distplot(layer_list, hist = True, kde = True,
                 kde_kws = {'linewidth': 2}, color=color)
    
    # compute mode of the histogram.
    mode_x = compute_mode(layer_list)
    
    # draw a vertical line at the mode of the histogram.
    plt.axvline(mode_x, color='blue', linestyle='dashed', linewidth=1.5)
    plt.text(mode_x, 0.16, 'mode: {:.4f}'.format(mode_x))

layer_list = [ 1.0,2.0,3.0,4.0,2.0,3.0,1.0,6.0,10.0,2.0]
make_density(layer_list, 'green')

在此处输入图片说明 I think the problem arises from the line plt.axvline(mode_x, color='blue', linestyle='dashed', linewidth=1.5) and plt.text(mode_x, 0.16, 'mode: {:.4f}'.format(mode_x)) .我认为问题出自plt.axvline(mode_x, color='blue', linestyle='dashed', linewidth=1.5)plt.text(mode_x, 0.16, 'mode: {:.4f}'.format(mode_x))

What am I doing wrong here?我在这里做错了什么?

Thank you,谢谢,

The main problem is that in compute_mode() plt.close() is called, which closes the plot that was just before created in make_density() .主要问题是在compute_mode() plt.close() ,它关闭了之前在make_density()创建的make_density() Note that sns.distplot is mainly a drawing function which shouldn't be used just for calculations.请注意, sns.distplot主要是一个绘图函数,不应仅用于计算。 As the kde was already plotted in make_density() , ax.lines[0] can be passed to compue_mode() to extract the curve data without the need for creating the plot a second time.由于 kde 已经在make_density()绘制, make_density() ax.lines[0]可以传递给compue_mode()以提取曲线数据,而无需再次创建绘图。

Some other remarks:其他一些说明:

  • In seaborn 0.11, distplot has be deprecated, and is replaced by two functions: histplot which creates a histogram, optionally with a kde.在 seaborn 0.11 中, distplot已被弃用,取而代之的是两个函数: histplot创建直方图,可选择使用 kde。 And displot (without "T") which creates a grid of histogram/kdeplots.displot (没有“T”),它创建了一个直方图/kdeplots 网格。 Apart from the name confusion, the kde_kws parameter of distplot is called line_kws in histplot , while kde_kws in histplot is meant for the function that calculates the KDE.除了名称混乱, kde_kws的参数distplot被称为line_kwshistplot ,而kde_kwshistplot是用于那些计算KDE功能。 Also, the kde curve always uses the same color as the histogram.此外,kde 曲线始终使用与直方图相同的颜色。
  • Seaborn's "axes level" functions return an ax that can be used for additional formatting. Seaborn的“轴水平”函数返回的ax ,可用于其他格式。 In your original code you added some labels before calling distplot , but as distplot also might change settings, it is safer to do all these formatting calls afterwards.在您的原始代码中,您在调用distplot之前添加了一些标签,但由于distplot也可能会更改设置,因此之后进行所有这些格式化调用会更安全。
  • You might want to read about the object-oriented interface and the difference between ax.set_xlabel() and plt.xlabel() .您可能想了解面向对象的接口以及ax.set_xlabel()plt.xlabel()之间的区别。
import matplotlib.pyplot as plt
import seaborn as sns

# a function to compute mode of the histograms shown in Figures `2` and `3` in the paper.
def compute_mode(line_object):
    x = line_object.get_xdata()
    y = line_object.get_ydata()
    mode_idx = y.argmax()
    return x[mode_idx], y[mode_idx]

# function to plot the histogram of the layer lists.
def make_density(layer_list, color):
    # Draw the histogram and fit a density plot.
    ax = sns.histplot(layer_list, kde=True,
                      line_kws={'linewidth': 2}, color=color)
    # compute mode of the histogram.
    mode_x, mode_y = compute_mode(ax.lines[0])

    # draw a vertical line at the mode of the histogram.
    ax.axvline(mode_x, color='blue', linestyle='dashed', linewidth=1.5)
    ax.text(mode_x, mode_y, 'mode: {:.4f}'.format(mode_x))
    # Plot formatting
    ax.set_xlabel('Median Stn. MC-Loss')
    ax.set_ylabel('Density')

layer_list = [1.0, 2.0, 3.0, 4.0, 2.0, 3.0, 1.0, 6.0, 10.0, 2.0]

make_density(layer_list, 'green')
plt.show()

示例图

Calling seaborn's distplot in compute_mode without specifying the ax messed with the plot.在计算模式中调用 seaborn 的 distplot 而不指定与绘图compute_mode的斧头。 You can simply replace compute_mode by this code:您可以简单地用以下代码替换compute_mode

def compute_mode(layer_list):
    dummy_fig, dummy_ax = plt.subplots()
    ax = sns.distplot(layer_list, hist=False, kde=True, kde_kws={'linewidth': 2}, ax=dummy_ax)
    x = ax.lines[0].get_xdata()
    y = ax.lines[0].get_ydata()
    mode_idx = y.argmax()
    mode_x = x[mode_idx]
    plt.close()

    return mode_x

Even if this workaround works, consider to compute the mode with dedicated tools like scipy's gaussian_kde .即使此解决方法有效,请考虑使用专用工具(如scipy 的 gaussian_kde )计算模式。 It will prevent you from messing with graphical libraries to do math stuff.它可以防止你搞乱图形库来做数学题。

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

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