Gautam
Gautam

Reputation: 2753

Limit the X and Y axes of ggplot2 plot

I'm using secondary axes (scaled) to show metric/imperial units for a plot. I'd like to have the plot area to be limited to (1500,0) and (5000,350) - both sets in principal coordinates. I've tried the following:

None of these made any change to my plot. I'd like to get rid of the areas highlighted by the red lines (crop the plot): enter image description here

Here's a minimal working example using mtcars - despite specifying the upper x-limit to be 10, the plot shows data past that range. I'd like the plot to cropped to the limits specified. Is there a way to do this?

ggplot(as.data.table(mtcars)) + 
  geom_line(aes(x = wt, y = mpg, color= factor(cyl))) + 
  ylab('Fuel Economy (mpg)') + 
  scale_y_continuous(sec.axis = sec_axis(~.*1.6/3.7854, name = 'Fuel Economy (kmpl)')) + 
  xlab('Weight (lbs)') + 
  scale_x_continuous(sec.axis = sec_axis(~./2.20462, name = 'Weight (kg)'), position = 'bottom') + 
  theme_light() + 
  theme(
    legend.position = c(0.15, 0.75),
    legend.title = element_blank(),
    axis.title.y.right = element_text(
      angle = 90,
      margin = margin(r = 0.8 * 11,
                      l = 0.8 * 11 / 2)
    )
  ) + 
  coord_cartesian(xlim = c(0, 5), ylim = c(10, 35))

enter image description here

Upvotes: 0

Views: 950

Answers (1)

Mohanasundaram
Mohanasundaram

Reputation: 2949

Add limits and expand arguments in scale_x_continuous and scale_y_continuous. You can add breaks as well.

ggplot(as.data.table(mtcars)) + 
  geom_line(aes(x = wt, y = mpg, color= factor(cyl))) + 
  ylab('Fuel Economy (mpg)') + 
  scale_y_continuous(limits = c(10, 35), expand = c(0, 0), 
                     sec.axis = sec_axis(~.*1.6/3.7854, name = 'Fuel Economy (kmpl)')
                     ) + 
  xlab('Weight (lbs)') + 
  scale_x_continuous(limits = c(0, 5), expand = c(0, 0), 
                     sec.axis = sec_axis(~./2.20462, name = 'Weight (kg)'), position = 'bottom') + 
  theme_light() + 
  theme(
    legend.position = c(0.15, 0.75),
    legend.title = element_blank(),
    axis.title.y.right = element_text(
      angle = 90,
      margin = margin(r = 0.8 * 11,
                      l = 0.8 * 11 / 2)
    )
  ) 

enter image description here

Upvotes: 1

Related Questions