r - 图例中二维密度图从0变为1
问题描述
- 我的目的——如何将图例中的二维密度图从0变为1。
- 我在这里生成了两个可变序列数据。我已经使用 实现了二维密度图
stat_density_2d
,像这样
p <- ggplot(df, aes(x=spi,y=crop))+
labs(title = "",y = "y", x = "x") +
#geom_raster() +
#geom_point() +
stat_density_2d(geom ="raster",aes(fill = ..density..),contour = F)
但是,图例“密度”显示为 0.05 到 0.2。我想将“密度”标准化为 [0,1] 的区间,其中 1 表示最高密度,0 表示最低密度。我如何对其进行编程,或者我如何处理原始数据以获得我想要的结果。
解决方案
这实际上很容易,您只需更改fill = ..density..
为fill = ..ndensity..
(注意:现代用法是stat(ndensity)
)。
示例数据的默认密度:
ggplot(faithful, aes(eruptions, waiting)) +
stat_density_2d(geom = "raster", aes(fill = stat(density)), contour = F)
密度缩放到 [0-1] 范围:
ggplot(faithful, aes(eruptions, waiting)) +
stat_density_2d(geom = "raster", aes(fill = stat(ndensity)), contour = F)
如果您明确希望在图例中包含 0:
ggplot(faithful, aes(eruptions, waiting)) +
stat_density_2d(geom = "raster", aes(fill = stat(ndensity)), contour = F) +
scale_fill_gradient(limits = c(0, NA))
这记录在 的“计算变量”下?stat_density_2d
。
推荐阅读
- svelte - 动态路由未检测到页面更改时 API 响应的更改
- google-sheets - Google Sheets Named Range - 引用单个单元格并启用下拉
- javascript - Discord.js 机器人自定义状态(收听、观看等)
- visual-studio-code - 在 vscode 中使用 pythontex
- python - 使用 Python 比较字符串
- sas - 带有空分隔符的 SAS CATX
- jenkins-pipeline - 詹金管道的全球代理是做什么的?
- python - discord.py - 检查是否找不到子命令
- hadoop - 分布式 Hbase 启动失败,错误信息:服务器尚未运行
- java - Java 处理无效请求映射 url,包括解码