Ggplot2: Flip axes and save data aspect ratio

In ggplot2, the coord_fixed() coordinate system ensures that the aspect ratio of the data is maintained at a given value. Thus, the shape of the panel changes to save the data form. Meanwhile, coord_flip() swaps the plots. However, the graph in ggplot2 must have exactly one coordinate system, so these functions cannot be combined.

My question is:

Is there a way to combine the behavior of coord_fixed() and coord_flip() , resulting in a coordinate system with exchangeable x and y axes and a fixed aspect ratio of the data?

This is a popular question, however the general answer is incorrect:

It is usually suggested to use coord_flip() along with theme(aspect.ratio = 1) instead of coord_fixed() . However, according to the ggplot2 documentation, this parameter refers to the "aspect ratio of the panel". Thus, the data will change shape to maintain the shape of the panel.

I suspect this is a function that does not currently exist in ggplot2. But more importantly, I believe that the right decision, or at least the answer to this question, should be documented.

A quick minimal problem example:

 library(ggplot2) x <- 1:100; data <- data.frame(x = x, y = x * 2) p <- ggplot(data, aes(x, y)) + geom_point() p # by default panel and data both fit to device window p + coord_fixed() # panel changes shape to maintain shape of data p + theme(aspect.ratio = 1) # data changes shape to maintain shape of panel p + coord_fixed() + coord_flip() # coord_flip() overwrites coord_fixed() # popular suggested answer does not maintain aspect ratio of data: p + coord_flip() + theme(aspect.ratio = 1) 
+5
source share
1 answer

I agree that the theme solution is actually not the right one. Here is a solution that works programmatically by calculating an aspect from the actual ranges of the axes stored in the plot object, but this requires a few lines of code:

 ranges <- ggplot_build(p)$layout$panel_ranges[[1]][c('x.range', 'y.range')] sizes <- sapply(ranges, diff) aspect <- sizes[1] / sizes[2] p + coord_flip() + theme(aspect.ratio = aspect) 

enter image description here

The solution that I would probably use in practice is to use horizontal geometers in the ggstance package (although this is not always possible).

Note. This will only give the exact correct answer for two continuous scales with equal extend multiplicative argument (i.e. by default).

+3
source

Source: https://habr.com/ru/post/1263969/


All Articles