I am trying to add captions outside the plots using the solutions from this
The idea is that I want to avoid having to set up the y parameter every time I change the data. Imagine that that the y-axis is different (it is something like this: 0.0000, 0.0005, 0.0010, 0.0015). In that case, the appropriate y would be -0.0005 because the "jump" is 0.0005, so I just have to make it negative.
For that reason, I was wondering if it is possible to get the COMPLETE vector of values from the y-axis.
For example, if we want to get all the values/breaks of the y-axis from the previous images would be: c(0.0, 0.2, 0.4, 0.6)
.
Does anyone know if I can get ALL the values from the y-axis of a plot?
Thanks in advance
CodePudding user response:
You can get the y axis breaks from the p
object like this:
as.numeric(na.omit(layer_scales(p)$y$break_positions()))
#> [1] 0.0 0.2 0.4 0.6
However, if you want the labels to be a fixed distance below the panel regardless of the y axis scale, it would be best to use a fixed fraction of the entire panel range rather than the breaks:
yrange <- layer_scales(p)$y$range$range
ypos <- min(yrange) - 0.2 * diff(yrange)
p coord_cartesian(clip = "off",
ylim = layer_scales(p)$y$range$range,
xlim = layer_scales(p)$x$range$range)
geom_text(data = caption_df,
aes(y = ypos, label = c(levels(data$Sex))))
For example, suppose you had a y scale that was twice the size:
p <- data %>%
ggplot(aes(value))
geom_density(lwd = 1.2, colour="red", show.legend = FALSE)
geom_histogram(aes(y= 2 * ..density.., fill = id), bins=10, col="black", alpha=0.2)
facet_grid(id ~ Sex )
xlab("type_data")
ylab("Density")
ggtitle("title")
guides(fill=guide_legend(title="legend_title"))
theme(strip.text.y = element_blank())
Then the exact same code would give you the exact same label placement, without any reference to breaks:
yrange <- layer_scales(p)$y$range$range
ypos <- min(yrange) - 0.2 * diff(yrange)
p coord_cartesian(clip = "off",
ylim = layer_scales(p)$y$range$range,
xlim = layer_scales(p)$x$range$range)
geom_text(data = caption_df,
aes(y = ypos, label = c(levels(data$Sex))))