如何解决无法显示seaborn distplot
我正在尝试使用seaborn
的{{1}}模块制作直方图和密度图,并且在该图上我还试图在模式下绘制一条垂直线。但是,结果图不会显示任何直方图和/或密度曲线。我的代码如下:
Python
我认为问题出在生产线上
# 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以及
distplot
和ax.set_xlabel()
之间的区别。
plt.xlabel()
,
在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)来计算模式。这样可以防止您将图形库弄乱以进行数学运算。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。