I would like to figure out how to get a y position that is relative to the scale of the ggplot produced.
For example:
library(ggplot)
marks <- data.frame(mpg = c(15,25,30), cyl = c(4,8,4))
ggplot()
geom_point(mtcars,mapping = aes(x = mpg, y = hp))
facet_grid(~cyl)
geom_point(marks, mapping = aes(x = mpg, y = Inf), col = "red")
Inserting Inf or -Inf will you the maximum and minimum extent of the plot. But what if I want 90%, which in this case would be probably around 330 maybe, however I do not want to hard code it.
CodePudding user response:
One option to achieve your desired result would be via the gggrid
package which similar to annotation_custom
allows to add your marks as grobs using relative coordinates but works with facets too:
library(ggplot2)
marks <- data.frame(mpg = c(15,25,30), cyl = c(4,8,4))
pg <- function(data, coords) {
grid::pointsGrob(x = coords$x, y = unit(rep(.9, length(coords$x)), "npc"),
gp = grid::gpar(col = "red", size = 1), pch = 16, size = unit(2, "mm"))
}
ggplot()
geom_point(mtcars,mapping = aes(x = mpg, y = hp))
facet_grid(~cyl)
gggrid::grid_panel(pg, data = marks, mapping = aes(x = mpg))
CodePudding user response:
Once you have created the plot you can get the range using the ggplot_build
function to find plot range. Not sure if you can access this without creating the plot as an object first.
library(ggplot)
marks <- data.frame(mpg = c(15,25,30), cyl = c(4,8,4))
p1 <- ggplot()
geom_point(mtcars,mapping = aes(x = mpg, y = hp))
facet_wrap(~cyl)
prange <- ggplot_build(p1)$layout$panel_params[[1]]$y$continuous_range
p1
geom_point(marks, mapping = aes(x = mpg, y = prange[1] (diff(prange)*0.9)), col = "red")