【问题标题】:Colour the background in seaborn kdeplot (python)在 seaborn kdeplot (python) 中为背景着色
【发布时间】:2021-05-20 06:52:44
【问题描述】:

我正在使用 seaborn 核密度估计来绘制概率密度等值线,如下所示:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

x = np.random.normal(0, 3, 100)
y = np.random.normal(0, 1, 100)

fig, ax = plt.subplots()

ax.scatter(x,y, marker='.')

ax.set_aspect('equal')
ax.set(xlim=(-13,13))
ax.set(ylim=(-8,8))


divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

sns.kdeplot(x,y, fill=True, shade_lowest=True, alpha=0.7, linewidths=3, \
            cmap='coolwarm', ax=ax, cbar=True, cbar_ax = cax)

colour = ax.collections[1].get_facecolor()

结果是:

我正在制作其中的许多,所以为了比较它们,我想固定地块限制。如您所见,我的问题是当我更改情节的限制时,seaborn 不会填充背景。

我的代码最后一行中的变量colour 包含我想要填充背景的内容。我需要帮助弄清楚如何做到这一点。我试过了

ax.set_facecolor(colour.reshape(4))

这当然需要工作才能达到我想要的:

这个问题与this 6 岁的问题基本相同,后者建议只删除最后一个轮廓下方的填充。我相信必须有一种方法来获得所需的行为。非常感谢任何帮助!

作为奖励:sns.kdeplot() 的 linewidths 参数什么都不做。如何更改等高线的线宽?

【问题讨论】:

  • 您可以使用cut 参数执行此操作,但可能需要一些试验和错误才能找到合适的值。

标签: python seaborn background-color kde


【解决方案1】:

正如@mwaskom 评论中所建议的,您可以使用cut parameter

使用 cut 参数可以部分避免这种情况,该参数指定 曲线应该超出极限数据点多远。但 这仅影响绘制曲线的位置;密度估计 仍然会在没有数据存在的范围内平滑,导致它 在分布的极端处人为地降低:

我通过反复试验获得了正确的 cut 值,即 12。有关详细信息,请参阅下面的代码。

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

x = np.random.normal(0, 3, 100)
y = np.random.normal(0, 1, 100)

fig, ax = plt.subplots()

ax.scatter(x,y, marker='.')

ax.set_aspect('equal')
ax.set(xlim=(-13,13))
ax.set(ylim=(-8,8))


divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

sns.kdeplot(x,y, fill=True, thresh=0, alpha=0.7, cmap='coolwarm', ax=ax, cbar=True, cbar_ax = cax, cut=12) # `shade_lowest` is now deprecated in favor of `thresh`
colour = ax.collections[1].get_facecolor()

输出图像:

【讨论】:

  • 谢谢杰。你对我写的作为奖金问题有什么建议吗? “线宽”参数似乎对我不起作用。
猜你喜欢
  • 2020-07-08
  • 2020-12-09
  • 1970-01-01
  • 2019-01-15
  • 2014-10-03
  • 2022-01-13
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多