Home > Software engineering >  Using scale_x_continuous in ggplot with x and y axis labels
Using scale_x_continuous in ggplot with x and y axis labels

Time:11-02

I have a ggplot with the x and y axis limited with scale_x_continuous. However, I also want to add x and y axis labels. This brings up this message:

Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.

I have also tried ylab = and xlab = in the labs 'section' but it also produced the same error. Any assistance would be greatly appreciated. This is my script:

MigrPlt = ggplot(Migr,aes(Distance3, `newBa`)) 
geom_line() 
scale_x_continuous(n.breaks = 10)  
xlim(0, 3800)  
ylim(0,25)   
labs(y= expression (paste('Ba:Ca (µmol mol'^~-1,')')), x = "Distance from Core (μm)")   
geom_hline(yintercept=2.25, linetype="dashed", color = "red")  
geom_vline(xintercept = 1193.9, linetype="dashed", color = "grey")  
geom_vline(xintercept = 1965.5, linetype="dashed", color = "grey")   
geom_vline(xintercept = 2616.9, linetype="dashed", color = "grey")   
geom_vline(xintercept = 3202.8, linetype="dashed", color = "grey")  
geom_vline(xintercept = 3698.9, linetype="dashed", color = "grey")

CodePudding user response:

xlim is a shortcut to the limits term of scale_x_XXXX, and it will overwrite any prior x scale settings. If you want to control the range of the x data, and the number of breaks, put both inside scale_x_continuous.

You might also consider using coord_cartesian() to control the axes -- the main difference is that it will keep all the input data, whereas using xlim or scale_x_continuous(limits = will filter out any data outside the specified range before it gets used by any geoms. This often surprises users who are using geom_smooth or geom_box or other summarizing geoms.

Compare:

ggplot(mtcars, aes(wt, mpg))  
  geom_point()  
  scale_x_continuous(n.breaks = 10) 

enter image description here

ggplot(mtcars, aes(wt, mpg))  
  geom_point()  
  scale_x_continuous(n.breaks = 10)  
  xlim(0, 10)
  # Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.

enter image description here

ggplot(mtcars, aes(wt, mpg))  
  geom_point()  
  scale_x_continuous(n.breaks = 10, limits = c(0, 10))

enter image description here

CodePudding user response:

Awesome! Thanks to Jon Spring's direction, I've got the answer! The correction for the section is as follows:

  scale_x_continuous(n.breaks = 10, limits = c(0, 7500))  scale_y_continuous(n.breaks = 10, limits = c(0,25))
  • Related