我需要使用 ggplot 在地图上插入多个点。我想在图例中显示与 point$types 中注册的类型相对应的颜色和形状的数量。我还需要将 point$obj 的值与坐标的插入一起打印在地图上。然而,我设法获取了该代码,但无法分配颜色和形状。如何解决这个问题呢?以下是绘图的示例:彩色坐标和打印标签:

这是代码:
library(geobr)
library(ggspatial)
library(ggplot2)
BR <- read_state(year=2018)
points
obj x y types
1 F1 -43.18669 -22.901724 A
2 F2 -43.31534 -22.779600 A
3 F3 -67.82527 -9.984939 B
4 F4 -72.74519 -7.610681 B
5 F5 -35.93844 -9.308399 B
6 F6 -63.13576 -4.105584 B
7 F7 -60.00568 -2.049304 B
8 F8 -35.91194 -7.217137 C
9 F9 -35.04254 -7.998586 C
10 F10 -48.26501 -18.889202 C
11 F11 -45.23610 -21.238526 D
12 F12 -43.71210 -22.244824 E
# plot
ggplot() +
geom_sf(
data=BR,
color="black",
size=.1, show.legend = T) +
geom_point(data=points,
aes(x=x, y= y, fill = as.factor(types)),
size = 3) +
scale_fill_manual(values=c("#999999","#000000", "#E69F00", "#56B4E9","#3399FF"))+
labs(x="Longitude", y="Latitude", fill = "Types", size=8 ) +
theme_bw()
Run Code Online (Sandbox Code Playgroud)
这是你想要的吗?
library(geobr)
library(ggspatial)
library(ggplot2)
library(ggrepel)
library(sf)
BR <- read_state(year=2018)
# plot
ggplot() +
geom_sf(data=BR,
color="black",
size=.1, show.legend = T) +
geom_point(data=points,
aes(x=x, y= y, color = types, size = types)) +
scale_color_manual(values=c("#999999","#000000", "#E69F00", "#56B4E9","#3399FF")) +
labs(x="Longitude", y="Latitude", color = "Types", size="Types") +
geom_label_repel(data=points, aes(x=x, y= y, label=obj)) +
theme_bw()
Run Code Online (Sandbox Code Playgroud)
要添加首都的名称,首先,我们需要计算每个州多边形的质心作为绘制其名称的坐标。
BR <- cbind(BR, st_coordinates(st_centroid(BR)))
Run Code Online (Sandbox Code Playgroud)
它会发出警告,基本上表明使用经度/纬度数据(即 WGS84)的质心坐标不准确,这对于绘图目的来说完全没问题。然后使用下面的代码
ggplot() +
geom_sf(data=BR,
color="black",
size=.1, show.legend = T) +
geom_text(data = BR, aes(X, Y, label = abbrev_state), colour = "black") +
geom_point(data=points,
aes(x=x, y= y, color = types, size = types)) +
scale_color_manual(values=c("#999999","#000000", "#E69F00", "#56B4E9","#3399FF")) +
labs(x="Longitude", y="Latitude", color = "Types", size="Types") +
geom_label_repel(data=points, aes(x=x, y= y, label=obj)) +
theme_bw()
Run Code Online (Sandbox Code Playgroud)
points <- structure(list(sl = 1:12, obj = c("F1", "F2", "F3", "F4", "F5",
"F6", "F7", "F8", "F9", "F10", "F11", "F12"), x = c(-43.18669,
-43.31534, -67.82527, -72.74519, -35.93844, -63.13576, -60.00568,
-35.91194, -35.04254, -48.26501, -45.2361, -43.7121), y = c(-22.901724,
-22.7796, -9.984939, -7.610681, -9.308399, -4.105584, -2.049304,
-7.217137, -7.998586, -18.889202, -21.238526, -22.244824), types = c("A",
"A", "B", "B", "B", "B", "B", "C", "C", "C", "D", "E")), class = "data.frame", row.names = c(NA,
-12L))
Run Code Online (Sandbox Code Playgroud)