#r #ggplot2 #gis #latitude-longitude #centroid
Вопрос:
Я сталкиваюсь с проблемой с geom_errorbar
аргументом, в котором я получаю ошибку Error: geom_errorbar requires the following missing aesthetics: x or y, xmin and xmax
.
У меня есть несколько наборов данных, и я хотел бы использовать их все для создания единой географической карты. Ниже приведен рабочий процесс и некоторые примеры данных. Желаемый график будет содержать данные о местоположении фона dat
, центроиды в centroids
и диапазоны ошибок x и y/стандартных отклонений для центроидов, которые вычисляются в centroids
кадре данных (т. Е. «Longitude_weighted_sd» и «Latitude_weighted_sd».
#packages
packages<-c('tidyverse','sf','rgdal','rnaturalearth','ggspatial','raster','sp', 'cowplot',
'dplyr','ggplot2','lubridate','stargazer', 'purrr', 'geosphere', 'purrr')
lapply(packages, library, character.only = T)
library(ggplot2)
library(sf)
library(rnaturalearth)
library(rgdal)
library(ggspatial)
library(spData)
library(cowplot)
library(tidyverse)
#download geographical and upload personal/mock data
world <- ne_countries(scale = "medium", returnclass = "sf")
states <- map_data("state")
data("us_states", package = "spData")
dat <- data.frame(Latitude = c(35.8, 35.85, 36.7, 35.2, 36.1, 35.859, 36.0, 37.0, 35.1, 35.2),
Longitude = c(-89.4, -89.5, -89.4, -89.8, -90, -89.63, -89.7, -89, -88.9, -89),
Period = c("early", "early", "early", "early", "early", "late", "late", "late", "late", "late"),
State = c("A", "A", "A", "T", "T", "T", "T", "A", "A", "A"))
#function to calculate weighted variance, sd, and se
weighted.var <- function(x, w = NULL, na.rm = FALSE) {
if (na.rm) {
na <- is.na(x) | is.na(w)
x <- x[!na]
w <- w[!na]
}
sum(w * (x - weighted.mean(x, w)) ^ 2) / (sum(w) - 1)
}
weighted.sd <- function(x, w, na.rm = TRUE) sqrt(weighted.var(x, w, na.rm = TRUE))
weighted.se <- function(x, w, na.rm = TRUE) sqrt(weighted.var(x, w, na.rm = TRUE))/sqrt(length(x))
#calculate centroids for "early" and "late" periods weighted by "State" observations
centroids <- dat %>%
group_by(Period, State) %>%
mutate(weight = 1/n()) %>%
group_by(Period) %>%
summarise(across(starts_with("L"),
list(weighted_mean = ~ weighted.mean(.x, w = weight),
weighted_sd = ~ weighted.sd(.x, w = weight),
weighted_se = ~ weighted.se(.x, w = weight))))
Если я выну geom_errorbar
аргумент, все будет отлично работать. Однако, когда я добавляю его, я получаю ошибку, которая geom_error requires the following missing aesthetics:x or y, xmin and xmax
, однако, заключается в том, что я думал, что все уточнил. Ниже приведен код ggplot2. Любая помощь будет очень признательна!
plot1 <- ggplot(data = world)
geom_sf(fill = "gray92") #light gray
geom_polygon(data = states, aes(x = long, y = lat, group = group), #states outline
color = "black", fill = NA)
geom_point(data = dat, aes(x = Longitude, y = Latitude, color = Period), #background data
alpha = 0.2, size = 1)
geom_point(data = centroids, aes(x = Longitude_weighted_mean, y = Latitude_weighted_mean,
fill = period), size = 6, pch = 21) #centroids
geom_errorbar(data = centroids,
aes(ymin = Latitude_weighted_mean - Latitude_weighted_sd,
ymax = Latitude_weighted_mean Latitude_weighted_sd,
xmin = Longitude_weighted_mean Longitude_weighted_sd,
xmax = Longitude_weighted_mean Longitude_weighted_sd), #errorbars
)
theme_bw()
coord_sf(crs = " proj=aea lat_1=29.5 lat_2=45.5 lat_0=37.5 lon_0=-96 x_0=0 y_0=0 ellps=GRS80 datum=NAD83 units=m no_defs")
coord_sf(xlim = c(-92, -88), ylim = c(33.5, 36.7), expand = TRUE)
theme(plot.title = element_text(size = 20),
legend.title = element_text(size = 20),
legend.text = element_text(size = 16),
axis.title = element_text(size = 20),
axis.text = element_text(size = 16),
axis.text.x = element_text(angle = 45, hjust = 1),
element_line(color = "black"))
annotate("text", label = "TN", size = 7, x = -88.3, y = 35.3)
annotate("text", label = "AR", size = 7, x = -91.7, y = 36)
annotate("text", label = "MS", size = 7, x = -89, y = 34)
xlab("Longitude") ylab("Latitude")
plot1
Заранее благодарю вас за всех, кто готов помочь. -нм
Комментарии:
1. Спасибо, что указали на это. Я добавил цитаты вокруг наблюдений за периодом и состоянием, чтобы сделать их воспроизводимыми.
Ответ №1:
Проблема в том, что вы пытаетесь двумя способами добавить строки ошибок через одну geom_errorbar
, и поскольку сообщение об ошибке сообщает вам, что вы не предоставили x
и не y
предоставили . Вместо этого я бы предложил добавить ваши строки ошибок через две geom_errorbar
строки, такие как:
library(ggplot2)
library(rnaturalearth)
library(tidyverse)
ggplot(data = world)
geom_sf(fill = "gray92") # light gray
geom_polygon(
data = states, aes(x = long, y = lat, group = group), # states outline
color = "black", fill = NA
)
geom_point(
data = dat, aes(x = Longitude, y = Latitude, color = Period), # background data
alpha = 0.2, size = 1
)
geom_point(data = centroids, aes(
x = Longitude_weighted_mean, y = Latitude_weighted_mean,
fill = Period
), size = 6, pch = 21) # centroids
geom_errorbar(
data = centroids,
aes(
x = Longitude_weighted_mean,
ymin = Latitude_weighted_mean - Latitude_weighted_sd,
ymax = Latitude_weighted_mean Latitude_weighted_sd
)
)
geom_errorbar(
data = centroids,
aes(
y = Latitude_weighted_mean,
xmin = Longitude_weighted_mean - Longitude_weighted_sd,
xmax = Longitude_weighted_mean Longitude_weighted_sd
)
)
theme_bw()
coord_sf(xlim = c(-92, -88), ylim = c(33.5, 36.7), expand = TRUE)
theme(
plot.title = element_text(size = 20),
legend.title = element_text(size = 20),
legend.text = element_text(size = 16),
axis.title = element_text(size = 20),
axis.text = element_text(size = 16),
axis.text.x = element_text(angle = 45, hjust = 1),
element_line(color = "black")
)
annotate("text", label = "TN", size = 7, x = -88.3, y = 35.3)
annotate("text", label = "AR", size = 7, x = -91.7, y = 36)
annotate("text", label = "MS", size = 7, x = -89, y = 34)
xlab("Longitude")
ylab("Latitude")