在發布這個問題之前,我非常小心,以避免任何重復。所以我打算創建一個基于季度的分面圖,配備主要和次要網格,而緯度和經度標簽僅在主要網格上。這是MWE:
library(sf)
library(rnaturalearth)
sf::sf_use_s2(FALSE)
dummy <- data.frame(
Lat1 = seq(-14.5, 4.5, by = 1),
Lon1 = seq(105.5, 124.5, by = 1),
quarter = rep(1:4, 10)
)
worldmap <- ne_countries(scale = 'medium', type = 'map_units', returnclass = 'sf')
wpp <- st_crop(worldmap, ymin = -15, ymax = -5, xmin = 105, xmax = 125)
minor.x <- seq(105, 125, by = 1)
minor.y <- seq(-15, -5, by = 1)
ggplot()
geom_sf(data = wpp, color = "gray", fill = "gray")
coord_sf(xlim=c(min(data.pie$Lon1-0.5),max(data.pie$Lon1) 0.5),
ylim=c(min(data.pie$Lat1)-0.5,max(data.pie$Lat1) 0.5),
expand = FALSE)
geom_hline(aes(yintercept = minor.y), color = "gray", linetype = "solid", size = 0.1)
geom_vline(aes(xintercept = minor.x), color = "gray", linetype = "solid", size = 0.1)
geom_point(data = dummy, aes(x = Lon1, y = Lat1), color= "black")
xlab("Longitude") ylab("Latitude")
scale_x_continuous(breaks = seq(105,125,2), minor_breaks = seq(106, 124, 2))
scale_y_continuous(breaks = seq(-15,-5,2), minor_breaks = seq(-14, -4, 2))
facet_wrap(~quarter)
theme_minimal()
theme(
# panel.grid.minor = element_line(color = "blue", size = 0.1),
panel.grid.major = element_blank(),
panel.background = element_rect(colour = "black", size=0.5),
legend.position = "right",
legend.title.align = 0.5,
legend.text.align = 1)
沒有刻面,我可以產生所需的輸出
但是,當我使用時facet_wrap(~quarter)出現錯誤:Error in FUN(X[[i]], ...) : subscript out of bounds
如果我關閉了,我設法生成了一個分面圖geom_vline,geom_hline但同時,我將失去對次要網格的控制(只顯示了主要網格。有什么解決方法嗎?PS。我使用的是最新的 R 和ggplot()版本.
uj5u.com熱心網友回復:
問題是你包裹x/yintercept在里面aes()。不是 100% 確定原因,但我的猜測是,當 ggplot2 進行分面時,它quarter也在尋找quarter傳遞給的資料中呼叫的列geom_hline/vline。但是,由于既沒有全域也沒有本地data,您會收到錯誤訊息。
作為這個問題的一個更最小的代表:
library(ggplot2)
ggplot()
geom_point(data = mtcars, aes(hp, mpg))
geom_point(aes(x = 1, y = 1), color = "red")
facet_wrap(~cyl)
#> Error in FUN(X[[i]], ...): subscript out of bounds
要解決您的問題,請將其設定x/yintercept為引數而不是美學。
library(sf)
library(rnaturalearth)
library(ggplot2)
ggplot()
geom_sf(data = wpp, color = "gray", fill = "gray")
coord_sf(
xlim = range(dummy$Lon1) c(-0.5, 0.5),
ylim = range(dummy$Lat1) c(-0.5, 0.5),
expand = FALSE
)
geom_hline(yintercept = minor.y, color = "gray", linetype = "solid", size = 0.1)
geom_vline(xintercept = minor.x, color = "gray", linetype = "solid", size = 0.1)
geom_point(data = dummy, aes(x = Lon1, y = Lat1), color = "black")
xlab("Longitude")
ylab("Latitude")
scale_x_continuous(breaks = seq(105, 125, 2), minor_breaks = seq(106, 124, 2))
scale_y_continuous(breaks = seq(-15, -5, 2), minor_breaks = seq(-14, -4, 2))
facet_wrap(~quarter)
theme_minimal()
theme(
# panel.grid.minor = element_line(color = "blue", size = 0.1),
panel.grid.major = element_blank(),
panel.background = element_rect(colour = "black", size = 0.5),
legend.position = "right",
legend.title.align = 0.5,
legend.text.align = 1
)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/436089.html
上一篇:如何使ggplot中的顏色更詳細
