带有ggmap的ggplot中stat_density2d的着色密度 [英] colouring density of stat_density2d in ggplot with ggmap

查看:60
本文介绍了带有ggmap的ggplot中stat_density2d的着色密度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的df由许多独特的个体组成,每个个体都有一个经纬度坐标点.

my df consists of a number of unique individuals each with a latitude and longitude coordinate point.

library(ggmap)
datParts = read.csv("smili_parts.csv", header=T, stringsAsFactors = TRUE)
SEmap = get_map(location = "thailand", zoom=3)
ggmap(SEmap) + geom_density2d(data=datParts, aes(x=q3b_longitude, y=q3b_latitude), size=0.3) + stat_density2d(data=datParts, aes(x=q3b_longitude, y=q3b_latitude), size=0.01, bins=16, geom="polygon") 

可以,但是我很想根据点的密度对密度多边形进行着色-也许红色代表高密度,而绿色代表低密度.

This is OK, but I would quite like the density polygons to be coloured based on the density of the points - maybe like red for high density compared to green for low density.

我尝试了

ggmap(SEmap) + geom_density2d(data=datParts, aes(x=q3b_longitude, y=q3b_latitude), size=0.3) + stat_density2d(data=datParts, aes(x=q3b_longitude, y=q3b_latitude, fill=..density..), size=0.01, bins=16, geom="polygon") 

Error in FUN(X[[i]], ...) : object 'density' not found

有没有办法做到这一点?谢谢你.

Is there a way to do this? thank you.

推荐答案

上周我不得不弄清楚这一点. geom_density2d 创建一个路径,根据定义,该路径没有填充.要填充,您需要一个多边形.因此,您需要调用 stat_density2d(geom ="polygon").而不是 geom_density2d .

I had to figure this out just last week for work. geom_density2d creates a path, which by definition has no fill. To get a fill, you need a polygon. So instead of geom_density2d, you need to call stat_density2d(geom = "polygon").

数据帧只是随机数据,具有很好的密度;您应该能够为您的地图改编相同的地图(我在制作一张非常相似的地图,因此使用 stat_density2d 应该没问题).

The dataframe is just random data that gave a nice density; you should be able to adapt the same for your map (I was making a very similar map for work, so using stat_density2d should be fine).

还请注意, calc(level) .. level .. 的替代品,但我认为它仅在 ggplot2 ,因此,如果您使用的是CRAN版本,只需将其替换为较旧的 .. level ..

Also note calc(level) is the replacement for ..level.., but I think it's only in the github version of ggplot2, so if you're using the CRAN version, just swap that for the older ..level..

library(tidyverse)

set.seed(1234)
df <- tibble(
    x = c(rnorm(100, 1, 3), rnorm(50, 2, 2.5)),
    y = c(rnorm(80, 5, 4), rnorm(30, 15, 2), rnorm(40, 2, 1)) %>% sample(150)
)

ggplot(df, aes(x = x, y = y)) +
    stat_density2d(aes(fill = calc(level)), geom = "polygon") +
    geom_point()

reprex软件包(v0.2.0)创建于2018-04-26.

Created on 2018-04-26 by the reprex package (v0.2.0).

这篇关于带有ggmap的ggplot中stat_density2d的着色密度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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