我想使用 sf 微调 ggplot2 中文本的 x 和 y 位置。文字的对齐可以在美学中修改,然后需要nudge也同样修改,但是nudge_x和nudge_y不能用于美学。
使用 sp 和强化数据框,我可以修改美学中的 x 和 y ( x=(x+hBump), y=(y+vBump) 。我不知道这在 sf 中是否可行。
以下是一些数据:
Cities <- read.table( text=
"City long lat hJust vJust hBump vBump
GrandJunction -108.550649 39.063871 1 1 -1100 -1000
Gunnison -106.925321 38.545825 0 1 0 -1000
Tincup -106.47836 38.754439 1 0 0 800",
header=TRUE )
Run Code Online (Sandbox Code Playgroud)
转换为 sf
Cities.sf <- st_as_sf(
x = Cities,
coords = c("long", "lat"),
crs = "+proj=longlat +datum=WGS84"
)
Run Code Online (Sandbox Code Playgroud)
ggplot(coord_sf 只是为了让标签不会脱落)
ggplot(Cities.sf) +
geom_sf() +
coord_sf(xlim = c(-109, -106.3), ylim = c(38.4, 39.2)) +
geom_sf_text(aes(label = City, hjust = hJust, vjust = vJust))
Run Code Online (Sandbox Code Playgroud)
现在,如果我们轻推其中一个,其他的可能会搞砸。需要审美的推动!
ggplot(Cities.sf) +
geom_sf() +
coord_sf(xlim = c(-109, -106.3), ylim = c(38.4, 39.2)) +
geom_sf_text(
aes(label = City, hjust = hJust, vjust = vJust),
nudge_x = 0.025, nudge_y = -0.025
)
Run Code Online (Sandbox Code Playgroud)
附带问题 - 我想如果我使用米将对象转换为另一个 crs,那么微调单位必须从度变为米?那就是 hBump 和 vBump 所在的单位。
@dc37 提供了做我想做的事的关键。对于更改坐标系的额外复杂性(因为 ggrepel 不能使用几何列表列):
转换为不同的CRS:
Cities.sf.t <- st_transform( Cities.sf, crs="+proj=laea +lon_0=-107.2 +lat_0=37.6 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs" )
Run Code Online (Sandbox Code Playgroud)
然后从几何列表列复制坐标并将它们作为 X 和 Y 列添加到数据框中,可用于文本标签:
Cities.sf.t <- cbind( Cities.sf.t, st_coordinates( Cities.sf.t ) )
Run Code Online (Sandbox Code Playgroud)
最后使用该数据框绘制绘图:
ggplot( Cities.sf.t ) + geom_sf() +
geom_text_repel( aes(x=X, y=Y, label=City) )
Run Code Online (Sandbox Code Playgroud)
ggrepel 允许使用 h/vjust 作为美学,但它们的行为不符合预期,而且我无法理解文档。我将不得不使用反复试验或只是接受它想要放置标签的位置。
据我所知,矢量输入nudge_x和nudge_y正确处理。
library(ggplot2)
library(sf)
#> Linking to GEOS 3.7.2, GDAL 2.4.2, PROJ 5.2.0
Cities <- read.table(text=
"City long lat hJust vJust hBump vBump
GrandJunction -108.550649 39.063871 1 1 -1100 -1000
Gunnison -106.925321 38.545825 0 1 0 -1000
Tincup -106.47836 38.754439 1 0 0 800",
header=TRUE)
Cities.sf <- st_as_sf(x = Cities,
coords = c("long", "lat"),
crs = "+proj=longlat +datum=WGS84")
ggplot(Cities.sf) + geom_sf() +
coord_sf(xlim = c(-109, -106.3), ylim = c(38.4, 39.2)) +
geom_sf_text(
aes(label = City, hjust = hJust, vjust = vJust),
nudge_x = c(-0.025, 0.025, -0.05),
nudge_y = c(-0.025, -0.025, 0)
)
#> Warning in st_point_on_surface.sfc(sf::st_zm(x)): st_point_on_surface may
#> not give correct results for longitude/latitude data
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020 年 1 月 1 日创建
| 归档时间: |
|
| 查看次数: |
1956 次 |
| 最近记录: |