我正在尝试使用 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
构建),但更平滑。
我累了:
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 :
是否可以按原样使用数据在 plotnine
中执行此操作,或者我是否需要进行额外的数据转换等?
最佳答案
您应该将填充
映射到密度
。 级别
由线划分,密度由区域划分。
(
...
+ stat_density_2d(aes(fill=after_stat('density')), geom='raster', contour=False)
)
然后设置插值方法对其进行平滑处理。
关于python - 使用plotnine绘制二维密度图(stat_密度_2d),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72424025/