图例中的二维密度图从0变为1 [英] two-dimensional density figure changes from 0 to 1 in the legend

查看:88
本文介绍了图例中的二维密度图从0变为1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我的目的-如何将图例中的二维密度图形从0更改为1.
  2. 我在此处生成了两个可变序列数据. 我已经使用stat_density_2d实现了二维密度图,像这样
  1. My purpose-How to change the two-dimensional density figure in the legend from 0 to 1.
  2. I have generated two variable sequence data here. I have realized the two-dimensioned density figures using stat_density_2d, like this

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表示最低密度.我该如何编程,或如何处理原始数据以获得所需的结果.

However, the legend "density" shows from 0.05 to 0.2. I want to normalize the "density" into an interval of [0,1], with 1 for the highest density and 0 for the lowest density. How do I program it, or what do I do with the raw data to get the results I want.

推荐答案

这实际上很容易,您只需将fill = ..density..更改为fill = ..ndensity..(注意:现代用法是stat(ndensity)).

This is actually quite easy, you simply change fill = ..density.. to fill = ..ndensity.. (note: modern usage is stat(ndensity)).

带有示例数据的默认密度:

Default density with example data:

ggplot(faithful, aes(eruptions, waiting)) +
  stat_density_2d(geom = "raster", aes(fill = stat(density)), contour = F)

密度缩放到[0-1]范围:

Density scaled to the [0-1] range:

ggplot(faithful, aes(eruptions, waiting)) +
  stat_density_2d(geom = "raster", aes(fill = stat(ndensity)), contour = F)

如果您想在图例中明确包含0:

And if you explicitly want to include 0 in your legend:

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的计算变量"下.

This is documented under 'computed variables' of ?stat_density_2d.

这篇关于图例中的二维密度图从0变为1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆