python - 使用plotnine绘制二维密度图(stat_密度_2d)

标签 python plotnine

我正在尝试使用 python 的 plotnine 沿着最后一个示例的行创建 2D 密度图:https://r-graph-gallery.com/2d-density-plot-with-ggplot2.html#:~:text=A%202d%20density%20plot%20is,of%20points%20in%20this%20fragment .

它应该大致如下所示(使用geom_bin2d构建),但更平滑。

enter image description here

我累了:

import pandas as pd
import numpy as np
from plotnine import *

df = pd.DataFrame({
    'x': np.random.normal(1,1,10000),
    'y': np.random.normal(3,2,10000),
})

p = (ggplot(df, aes('x','y'))
  + theme_light()
  + stat_density_2d(aes(fill='..level..'), geom='raster', contour=False)
  + labs(x=None,y=None)
)
p

但最终只有一个黄色 Blob :

enter image description here

是否可以按原样使用数据在 plotnine 中执行此操作,或者我是否需要进行额外的数据转换等?

最佳答案

您应该将填充映射到密度级别由线划分,密度由区域划分。

(
...
+ stat_density_2d(aes(fill=after_stat('density')), geom='raster', contour=False)
)

然后设置插值方法对其进行平滑处理。

关于python - 使用plotnine绘制二维密度图(stat_密度_2d),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72424025/

相关文章:

python - 如何在plotnine中移动轴标签?

python - 捕获组之间的字符串,组不固定(正则表达式)

python - 在从 Excel 范围填充的嵌套元组上使用 join()

python - Python 中是否有 gridExtra/cowplot 类型包与 Plotnine 一起使用以对齐子图(即边际分布)

python - Plotnine 的比例填充和轴位置

python - 有没有办法防止 plotnine 在将 ggplot 对象保存到文件时打印用户警告?

python - 为什么在 'and' 、 'or' 等处没有 python 隐式续行?

python - 仅当过去 4 小时内没有重复项时才插入表中

python - 如何子类化构建命令?

python - 使用 Plotnine 在 Python 中绘制 QQ 绘图