我在用sfggplot2做 map .是否可以调整X轴,以便我可以:

1-精确到我想要的休息次数(在本例中为4)

2-使第一个和最后一个标签从轴的起点和结尾处开始(即与绘图边框没有间隙)

library(ggplot2)
library(sf)
#> Linking to GEOS 3.11.1, GDAL 3.6.2, PROJ 9.1.1; sf_use_s2() is TRUE
library(patchwork)

poly <- rnaturalearth::ne_countries(
  country = c("Canada", "Belgium"),
  scale = "medium",
  returnclass = "sf"
)

make_plot <- function(poly) {
  bbox <- st_bbox(poly)

  xmin <- bbox[1]
  xmax <- bbox[3]

  xbreaks <- pretty(seq(xmin, xmax, length.out = 4), n = 4)

  ggplot() +
    geom_sf(data = poly) +
    scale_x_continuous(breaks = xbreaks) +
    coord_sf(xlim = c(xmin, xmax), expand = FALSE)
}

p1 <- make_plot(poly[poly$name_en == "Canada", ])
p2 <- make_plot(poly[poly$name_en == "Belgium", ])

p1 + p2

创建于2023-04-14年第reprex v2.0.2

推荐答案

这应该很近了.您可能需要调整x轴标签的显示方式.不过要小心,人们可能会对 map 敏感.

pretty函数并没有一致地返回x轴上的四个不同的数字.

library(ggplot2)
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
#> Linking to GEOS 3.11.1, GDAL 3.6.2, PROJ 9.1.1; sf_use_s2() is TRUE
library(patchwork)

poly <- rnaturalearth::ne_countries(
  country = c("Canada", "Belgium"),
  scale = "medium",
  returnclass = "sf"
)

make_plot <- function(poly) {
  bbox <- st_bbox(poly)
  
  # rounding the xmin & xmax to 2 decimal places
  xmin <- bbox[1] %>% round(2)
  xmax <- bbox[3] %>% round(2)
  
  xbreaks <- seq(xmin, xmax, length.out = 4)
  
  ggplot() +
    geom_sf(data = poly) +
    scale_x_continuous(breaks = xbreaks) +
    coord_sf(xlim = c(xmin, xmax), expand = FALSE)
}

# had to change the subsetting, may be due to package version difference.
p1 <- make_plot(poly[poly$name == "Canada", ])
p2 <- make_plot(poly[poly$name == "Belgium", ])

p1 + p2

reprex package(v2.0.1)于2023-04-14创建

R相关问答推荐

在Julia中调用R函数

使用gggplot 2在R中重新调整面板和y轴文本大小

ggplot 2中的地块底图(basemaps_gglayer()不起作用)

咕噜中的元素列表:map

编辑文件后编辑RhandsonTable

如何按排序顺序打印一个框架中所有精确的唯一值?

R for循环返回到先前值

为什么在ggplot2中添加geom_text这么慢?

R中插入符号训练函数的中心因子和尺度因子预测

如何从容器函数中提取conf并添加到ggplot2中?

过滤名称以特定字符串开头的文件

`夹心::vcovCL`不等于`AER::tobit`标准错误

在不对R中的变量分组的情况下取两行的平均值

如何为混合模型输出绘制不同的线型?

R预测包如何处理ARIMA(Auto.arima函数)中的缺失值

使用同一行中的前一个值填充R矩阵中的缺失值

Broom.Mixed::Augment不适用于Sample::分析

roxygen2正在处理太多的文件

隐藏基于 case 总数的值

我有2011-2022年的年度数据.如何计算最低年份和最高年份之间的差额?