Assuming the desired labels can't be determined until print time (perhaps by inspecting the graphics device?), it sounds like you want to be leveraging/creating a custom ggplot2 geom extension like ggrepel. If ggrepel isn't what you need, you can learn about creating your own geom here.
To answer the question in the title: "how to access ggplot’s inherited data object from a layer", you can always use ggplot_build()
to get a data structure sufficient for describing the plot, which includes each layer of data:
library(ggplot2)
library(sf)
library(albersusa)
usa <- usa_sf("laea")
# st_centroid gets the center POINT of polygons
uscenter <- st_centroid(usa)
p <- ggplot() +
geom_sf(data = usa) +
geom_sf(data = uscenter)
b <- ggplot_build(p)
identical(usa, b$plot$layers[[1]]$data)
#> [1] TRUE
identical(usa, b$plot$layers[[2]]$data)
#> [1] TRUE
I'm not sure how that gets you any closer to the goal of only showing labels for certain points, though. You'd probably need to hack into ggplot_gtable()
which is the actual grid object ggplot2 passes onto grid to do the drawing (assuming you don't want to go the custom geom route):
> ggplot_gtable(b)
TableGrob (10 x 7) "layout": 17 grobs
z cells name grob
1 0 ( 1-10, 1- 7) background rect[plot.background..rect.274]
2 5 ( 5- 5, 3- 3) spacer zeroGrob[NULL]
3 7 ( 6- 6, 3- 3) axis-l absoluteGrob[GRID.absoluteGrob.268]
4 3 ( 7- 7, 3- 3) spacer zeroGrob[NULL]
5 6 ( 5- 5, 4- 4) axis-t null[GRID.null.254]
6 1 ( 6- 6, 4- 4) panel gTree[panel-1.gTree.253]
7 9 ( 7- 7, 4- 4) axis-b absoluteGrob[GRID.absoluteGrob.261]
8 4 ( 5- 5, 5- 5) spacer zeroGrob[NULL]
9 8 ( 6- 6, 5- 5) axis-r null[GRID.null.269]
10 2 ( 7- 7, 5- 5) spacer zeroGrob[NULL]
11 10 ( 4- 4, 4- 4) xlab-t zeroGrob[NULL]
12 11 ( 8- 8, 4- 4) xlab-b zeroGrob[NULL]
13 12 ( 6- 6, 2- 2) ylab-l zeroGrob[NULL]
14 13 ( 6- 6, 6- 6) ylab-r zeroGrob[NULL]
15 14 ( 3- 3, 4- 4) subtitle zeroGrob[plot.subtitle..zeroGrob.271]
16 15 ( 2- 2, 4- 4) title zeroGrob[plot.title..zeroGrob.270]
17 16 ( 9- 9, 4- 4) caption zeroGrob[plot.caption..zeroGrob.272]