Home > Software design >  Preserving Slope after Changing Axis Limits (ggplot)?
Preserving Slope after Changing Axis Limits (ggplot)?

Time:01-31

Here is some hypothetical data:

data <- tibble(x=seq(1:20),
               y=c(55, 50, 45, 40, 42.5, 38, 35, 30, 29.5, 27, 
                     25, 23, 20, 15, 14, 12.5, 11, 8, 7, 6))

I would like to plot it on a logarithmic scale as such:

plot <- ggplot(data, aes(x, y))  
  geom_point()  
  geom_line()  
  scale_y_continuous(trans='log10', 
                     limits = c(1,100))  
  scale_x_continuous(breaks = seq(1,20, by=1),
                     limits = c(1,20))  
  theme_classic()  
  theme(aspect.ratio = 2)

plot

enter image description here

I intentionally set the aspect ratio to 2 (i.e. 2:1 y:x) . I would like to essentially truncate the y-axis to a minimum of 5 and a maximum of 60, however I want to preserve the same scaling factors. I don't want the new plot to have a 2:1 aspect ratio, but rather for it to be a "cropped" version of the full plot with a 2:1 aspect ratio. In other words, I don't want the slope of the line to change. However, when I try to adjust the limits of the y-axis, like below, the aspect ratio of 2:1, rather than the scaling factor (slope), is preserved. Is there any way to get around this? Thanks.

plot2 <- plot   ylim(5, 60)


plot2

enter image description here

CodePudding user response:

You could manually adjust the plot's dimensions by specifying the height and width using the ggplot function to "crop" the plot while maintaining the scaling factors. For instance:

plot <- ggplot(data, aes(x, y))  
  geom_point()  
  geom_line()  
  scale_y_continuous(limits = c(5,60), trans='log10')  
  scale_x_continuous(limits = c(1,20), breaks = seq(1,20, by=1))  
  coord_cartesian(ylim = c(5, 60))  
  theme_classic()

plot

enter image description here

CodePudding user response:

If you wish to preserve the slope of the line, then instead of using aspect.ratio, you can use coord_fixed, changing only the y limits:

plot <- ggplot(data, aes(x, y))  
  geom_point()  
  geom_line()  
  scale_y_continuous(trans='log10', 
                     limits = c(1,100))  
  scale_x_continuous(breaks = seq(1,20, by=1),
                     limits = c(1,20))  
  theme_classic() 

plot   coord_fixed(10)

plot   coord_fixed(10, ylim = c(5, 60))

Created on 2023-01-30 with reprex v2.0.2

  • Related