user438383
user438383

Reputation: 6206

colouring density of stat_density2d in ggplot with ggmap

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") 

enter image description here

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.

I tried

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.

Upvotes: 0

Views: 950

Answers (1)

camille
camille

Reputation: 16842

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").

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).

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()

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

Upvotes: 1

Related Questions