更改默认颜色并删除geom_density2d()图中的图例

时间:2018-02-05 16:33:02

标签: r ggplot2 ggmap

在下面的代码中,如何删除第二个图例(对于alpha级别,我认为)并将默认的蓝色更改为红色?

suppressMessages(library(ggmap))
data(crime)
houston.map <- get_map(location = geocode("Houston"),
                       zoom = 14)
ggmap(houston.map, extent = "device", legend = "topleft") +
  stat_density2d(data = crime,
                 aes(x = lon, y = lat, fill = ..level.., alpha = ..level..),
                 size = 2,
                 bins = 10,
                 geom = "polygon") +
  labs(fill = "Density")

enter image description here 感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用guides图层删除第二个图例,将alpha指定为FALSE,然后您可以使用scale_fill_gradient更改颜色比例完成如下:

ggmap(houston.map, extent = "device", legend = "topleft") +
  stat_density2d(data = crime,
                 aes(x = lon, y = lat, fill = ..level.., alpha = ..level..),
                 size = 2,
                 bins = 10,
                 geom = "polygon") +
  scale_fill_gradient(low = "#333333", high = "#cc0000") +
  labs(fill = "Density") +
  guides(alpha = F)

答案 1 :(得分:1)

添加guides(alpha = F)会删除该图例。

suppressMessages(library(ggmap))
data(crime)
houston.map <- get_map(location = geocode("Houston"),
                       zoom = 14)
ggmap(houston.map, extent = "device", legend = "topleft") +
  stat_density2d(data = crime,
                 aes(x = lon, y = lat, fill = ..level.., alpha = ..level..),
                 size = 2,
                 bins = 10,
                 geom = "polygon") +
  guides(alpha = F) + 
  labs(fill = "Density")