图例在 ggplot geom_sf 中显示错误颜色

问题描述 投票:0回答:1

我正在制作一张地图,我需要一些城市作为某种颜色的点(A 城市),一些城市作为不同颜色的点(B 城市)。所有 B 城市也在 A 列表中,因此我将 B geom_sf 放在第二位,以便这些点将分层在 A 城市之上。

在地图本身上,这有效,橙色点在其他点之上可见。但在传说中,A 和 B 都是橙色的。我需要 A 为深色!

(请忽略地图的其他美观问题哈哈,我会到达那里)

sample map showing issue

usa_states <- map_data("state") %>%
  rename(lon=long, State=region, County=subregion)

Acities <- read_csv("Acities.csv")
Acities_sf <- st_as_sf(Acities, coords = c("lon", "lat"), crs = 4326)

Bcities <- read_csv("Bcities.csv")
Bcities_sf <- st_as_sf(Bcities, coords = c("lon", "lat"), crs=4326)

AandBmap <- ggplot() + geom_polygon(data=usa_states, aes(x=lon, y=lat, group=group), fill="#DAD9D5", color="white") + #this is a gray US background
  coord_quickmap() + 
  geom_sf(data=Acities_sf, color = "#174337", size = 1.5, aes(fill="A Location")) + #A cities
  geom_sf(data=Bcities_sf, color = "#EAAA1B", size = 1.5, aes(fill="A and B Location")) + #B cities
  guides(fill=guide_legend(title=NULL)) +
  labs(x=NULL, y=NULL) + 
  theme_void()
AandBmap

抱歉,我不知道如何/在哪里上传我的样本数据,如果有人可以向我指出,我可以做到。与此同时,这应该可以工作,而不是加载 csv。

Acities <- matrix(c(34.0549, -118.243, 38.9072, -77.0369, 29.9511, -90.0715, 40.8137, -96.7026, 40.7128, -74.006), nrow=5, ncol=2, byrow=TRUE)

Acities <- matrix(c(34.0549, -118.243, 40.7128, -74.006), nrow=2, ncol=2, byrow=TRUE)
r ggplot2 legend ggmap geom-sf
1个回答
0
投票

问题是您已将颜色设置为

aes()
外部的参数,然后将所需的标签映射到
fill
内的
aes()
aes 上。相反,您必须映射到
color
aes 并使用
scale_color_manual
设置所需的颜色和标签。此外,您可以通过将城市数据绑定到一个数据帧并添加城市的标识符列来简化:

library(ggplot2)
library(sf)
#> Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
library(maps)
library(dplyr, warn = FALSE)

Acities <- as.data.frame(Acities)
Bcities <- as.data.frame(Bcities)
names(Acities) <- names(Bcities) <- c("lon", "lat")

usa_states <- map_data("state") %>%
  rename(lon = long, State = region, County = subregion)

AB_cities <- list(A = Acities, B = Bcities) |>
  dplyr::bind_rows(.id = "city")

AB_cities_sf <- AB_cities |>
  st_as_sf(coords = c("lon", "lat"), crs = 4326)

ggplot() +
  geom_polygon(
    data = usa_states, aes(x = lon, y = lat, group = group),
    fill = "#DAD9D5", color = "white"
  ) +
  geom_sf(data = AB_cities_sf, size = 1.5, aes(color = city)) +
  scale_color_manual(
    values = c(A = "#174337", B = "#EAAA1B"),
    labels = c(A = "A Location", B = "A and B Location")
  ) +
  guides(fill = guide_legend(title = NULL)) +
  labs(x = NULL, y = NULL) +
  theme_void()

© www.soinside.com 2019 - 2024. All rights reserved.