我在使用 ggplot2 創建的英國地圖上將物種發生記錄繪制為點。在我的 csv 中,有一列記錄年份 - 如何添加過濾器以便僅繪制特定年份/年份范圍內的記錄而不是所有記錄?代碼如下,對地圖設計很滿意,只想繪制一些記錄!
library(ggplot2)
library("sf")
library(rnaturalearth)
library(rnaturalearthdata)
library(ggspatial)
book1points <- read.csv("removeddirectoryforprivacy.csv")
theme_set(theme_bw())
world <- ne_countries(scale = "medium", returnclass = "sf")
class(world)
ggplot(data = world)
geom_sf()
geom_point(data = book1points, aes(x = lon, y = lat), size = 0.4, shape = 22, fill = "darkred")
xlab("Longitude") ylab("Latitude")
ggtitle("Book1")
annotation_scale(location = "bl", width_hint = 0.3)
annotation_north_arrow(location = "bl", which_north = "true",
pad_x = unit(0.22, "in"), pad_y = unit(0.2, "in"),
style = north_arrow_fancy_orienteering)
coord_sf(xlim=c(-11.5,3), ylim=c(49,61), expand = FALSE)
theme(panel.grid.major = element_line(color = gray(0.5), linetype = "dashed", size = 0.2), panel.background = element_rect(fill = "aliceblue"))
uj5u.com熱心網友回復:
正如@GregorThomas 提到的,你想給出ggplot一個子集。您可以filter在geom_point.
library(tidyverse)
library(sf)
library(rnaturalearth)
library(rnaturalearthdata)
library(ggspatial)
ggplot(data = world)
geom_sf()
geom_point(
data = book1points %>% dplyr::filter(year == 2021),
aes(x = lon, y = lat),
size = 0.4,
shape = 22,
fill = "darkred"
)
xlab("Longitude") ylab("Latitude")
ggtitle("Book1")
annotation_scale(location = "bl", width_hint = 0.3)
annotation_north_arrow(
location = "bl",
which_north = "true",
pad_x = unit(0.22, "in"),
pad_y = unit(0.2, "in"),
style = north_arrow_fancy_orienteering
)
coord_sf(xlim = c(-11.5, 3),
ylim = c(49, 61),
expand = FALSE)
theme(
panel.grid.major = element_line(
color = gray(0.5),
linetype = "dashed",
size = 0.2
),
panel.background = element_rect(fill = "aliceblue")
)
輸出

或者,如果您有多年,那么您可以使用:
data = book1points %>% dplyr::filter(year %in% 2020:2021)
或者如@GregorThomas 提供的那樣,您也可以在該行中使用基數 R 而不是dplyr.
data = subset(book1points, year == 2020)
data = subset(book1points, year %in% 2020:2021)
資料
book1points <- structure(list(
lon = c(-2.1767,-0.44086,-2.791934,-1.253848,-0.253848),
lat = c(54.236969, 53.144121, 52.386316, 52.932735,
52.932735),
year = c(2020, 2021, 2020, 2021, 2021)
),
class = "data.frame",
row.names = c(NA,-5L))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/384669.html
