How to fix the aspect ratio in ggplot?

前端 未结 3 1134
忘了有多久
忘了有多久 2020-11-30 20:18

I\'m trying to resize a plot to fit into my document, but I\'m having difficulties getting the plotted diagram do be a square.

Example:

pdf(file = \"         


        
3条回答
  •  时光说笑
    2020-11-30 20:39

    To ensure a particular aspect ratio, e.g. for square, use theme(aspect.ratio=1).

    Andrie's answer doesn't give the full picture, as the example provides perhaps unnatural data where range of x equals the range of y. If however the data were:

    df <- data.frame(
      x = runif(100, 0, 50),
      y = runif(100, 0, 5))
    ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed()
    

    then the plot would look like this:

    enter image description here

    The coord_fixed() function also has an argument to adjust the ratio of axes:

    ratio aspect ratio, expressed as y / x

    So that the plot could be made square with:

    ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed(ratio=10)
    

    enter image description here

    But you need to adjust this with the limits of the variables or plot area (not all limits are nicely divisible by whole numbers like these examples).

提交回复
热议问题