您可以在下面的图片中看到“颜色”图例无法正常运行。我期望有一个彩色圆圈(例如,一个颜色应该是绿色圆圈),但是背景是绿色的,您可以看到似乎是某种类型的边界框的黑色覆盖。
这是我的代码:
library(ggmap)
c_map <- c(left = -86.817417, bottom = 36.133247, right = -86.793141, top = 36.153650)
campus <- get_stamenmap(c_map, zoom = 15, maptype = "toner-lines")
some_data <- read.csv('https://gist.githubusercontent.com/pconwell/085c1413e418adaa7c1e203c9680a0f8/raw/c7a3e5f7aa900de6bc2bcccd5dc5d9b8f7e31b81/some_data.csv')
ggmap(campus, darken = c(0.33, "white"), extent = "device") +
stat_density2d(data = some_data,
aes(x = longitude,
y = latitude,
fill = stat(nlevel),
alpha = stat(nlevel)),
size = 2,
bins = 12,
geom = "polygon"
) +
scale_fill_gradientn(guide = "colorbar",
colours = c("#adddd1", "#3e98af", "#375980"),
breaks=c(0.2, 0.9),
labels=c("Least","Most"),
name = "Heat Map"
) +
geom_point(data = some_data,
aes(x = longitude,
y = latitude,
color = color,
shape = shape),
alpha = .75,
size = 4
) +
scale_alpha_continuous(range = c(0.33, 0.66),
guide = FALSE
)
如何获得图例以正确显示颜色?图标在地图中正确显示,但在图例中未正确显示。
答案 0 :(得分:3)
该问题的简化版本(删除了ggmap
和Google API密钥的要求)表明,该问题主要与多余的参数有关。稍后将代码分开,因为这些层构成了图例中包含的内容。 stat_density2d
中的size参数在将geom设置为polygon时不执行任何操作;仅对轮廓有意义,例如:
library(ggplot2)
some_data <- read.csv('https://gist.githubusercontent.com/pconwell/085c1413e418adaa7c1e203c9680a0f8/raw/c7a3e5f7aa900de6bc2bcccd5dc5d9b8f7e31b81/some_data.csv')
ggplot(some_data, aes(x = longitude, y = latitude)) +
geom_point(aes(color = color, shape = shape), alpha = 0.75, size = 4) +
stat_density2d(aes(alpha = stat(nlevel)),
size = 2) +
guides(alpha = "none",
color = guide_legend(override.aes = list(fill = NA)))
您会看到size = 2
在浓度和图例中的效果,它在颜色图例中显示为粗线。
由于这对于多边形而言不是必需的,因此请删除size参数或将其设置为0。您还从密度层引入了fill元素,使图例上的区域变暗。通过在图例中将填充明确设置为NA
来删除该填充。
ggplot(some_data, aes(x = longitude, y = latitude)) +
geom_point(aes(color = color, shape = shape), alpha = 0.75, size = 4) +
stat_density2d(aes(fill = stat(nlevel), alpha = stat(nlevel)),
size = 0,
geom = "polygon") +
guides(alpha = "none",
color = guide_legend(override.aes = list(fill = NA)))
答案 1 :(得分:1)
背景和边框来自图例以显示多边形的颜色。这是一个更简单的可重现示例:
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.5.3
set.seed(42)
df <- as.data.frame(MASS::mvrnorm(100, c(0, 0), matrix(c(1, .6), 2, 2)))
ggplot(df, aes(V1, V2)) +
stat_density_2d(geom = "polygon") +
geom_point(aes(colour = cut_number(V1, 5)))
您可以通过显式设置多边形几何的颜色来解决此问题:
ggplot(df, aes(V1, V2)) +
stat_density_2d(geom = "polygon", colour = NA) +
geom_point(aes(colour = cut_number(V1, 5)))
但是,即使相关图层没有任何颜色映射,多边形显示图例还是让我有些惊讶。也许这是一个错误?
更新:我无法用其他几何图形或统计数据重现此行为,因此我进一步研究了密度2d:奇怪的是,似乎出现了多边形的颜色图例,因为{ {1}}具有默认的颜色美学价值:
StatDensity2d
由reprex package(v0.3.0)于2019-07-04创建