Home > Enterprise >  How can I get the real scale from a facet_grid plot in R?
How can I get the real scale from a facet_grid plot in R?

Time:03-22

I am trying to add captions as it appears in this image1

plot_info <- layer_data(p)
> min(plot_info$density)
[1] 7.166349e-09
> max(plot_info$density)
[1] 0.5738021

As you can see in the plot, the y-axis starts at 0 and if finishes around 0.7 more less. However, the maximum density is 0.57.

If I try to use the info from layer_data:

p   coord_cartesian(clip="off", ylim=c(min(plot_info$density), max(plot_info$density)), 
                  xlim = c(min(plot_info$x), max(plot_info$x)))

The plot changes completely.

enter image description here

Does anyone know how can I get the scales that ggplot2 and facet_grid are using? I need the information of the density (y_axis) and the info from the x_axis.

Thanks in advance

CodePudding user response:

Yes, to get the scales directly, use layer_scales(p), which gives you the range of the axes rather than just the range of the data, which is what you get from layer_data(p)

p   coord_cartesian(clip = "off", 
                    ylim = layer_scales(p)$y$range$range, 
                    xlim = layer_scales(p)$x$range$range)

enter image description here

Or, to combine this question with your last, where you add the text labels outside of the plotting panels, your result might be something like:

p   coord_cartesian(clip = "off", 
                    ylim = layer_scales(p)$y$range$range, 
                    xlim = layer_scales(p)$x$range$range)  
  geom_text(data = data.frame(value = c(0, 6), id = c("df2", "df2"),
                              Sex = c('Female', 'Male')),
            aes(y = -0.15, label = c('Female', 'Male')))

enter image description here

CodePudding user response:

Does this help?

?layer_data
summary(layer_data(p, i = 2))

i is the layer you want to return

Can min the xmin and max the xmax etc

  • Related