无法显示seaborn distplot

问题描述

我正在尝试使用seaborn的{​​{1}}模块制作直方图和密度图,并且在该图上我还试图在模式下绘制一条垂直线。但是,结果图不会显示任何直方图和/或密度曲线。我的代码如下:

Python

enter image description here

我认为问题出在生产线上 # 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,1.0,6.0,10.0,2.0] make_density(layer_list,'green') plt.axvline(mode_x,linewidth=1.5)

我在做什么错了?

谢谢

解决方法

主要问题是在compute_mode()中调用了plt.close(),从而关闭了在make_density()中创建之前的绘图。请注意,sns.distplot主要是一个绘图函数,不应仅用于计算。由于kde已在make_density()中绘制,因此ax.lines[0]可以传递到compue_mode()以提取曲线数据,而无需再次创建图。

其他一些评论:

  • 在seaborn 0.11中,distplot已被弃用,并被两个函数取代:histplot可创建直方图,并可选地使用kde。 displot(不带“ T”)将创建一个直方图/ k展开图网格。除了名称混乱之外,kde_kws的{​​{1}}参数在distplot中被称为line_kws,而histplot中的kde_kws则用于该函数计算KDE。另外,kde曲线始终使用与直方图相同的颜色。
  • Seaborn的“轴级”函数返回一个histplot,可用于其他格式。在您的原始代码中,您在调用ax之前添加了一些标签,但是由于distplot也可能会更改设置,因此以后进行所有这些格式化调用会更安全。
  • 您可能想了解object-oriented interface以及distplotax.set_xlabel()之间的区别。
plt.xlabel()

example plot

,

compute_mode中调用seaborn的distplot,而未指定与该图混淆的斧头。您只需将以下代码替换为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

即使该解决方法可行,也请考虑使用专用工具(例如scipy's gaussian_kde)来计算模式。这样可以防止您将图形库弄乱以进行数学运算。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...