ggplot2: Flip axes and maintain aspect ratio of data

后端 未结 1 687
小蘑菇
小蘑菇 2020-12-11 17:36

In ggplot2, the coord_fixed() coordinate system ensures that the aspect ratio of the data is maintained at a given value. So, the shape of the panel changes to

相关标签:
1条回答
  • I agree that the theme solution isn't really a proper one. Here is a solution that does work programatically by calculating the aspect from the actual axes ranges stored in the plot object, but it takes 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)
    

    The solution I would probably use in practice, is to use the horizontal geoms in the ggstance package (although this may not always be feasible).

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

    edit: In many cases I would recommend using coord_equal combined with the ggstance package instead of this solution.

    0 讨论(0)
提交回复
热议问题