Search code examples
plotaxis

Adjusting the plot axis range and intervals


I am new to 'R' but have started to produce some useful plots. My query is how do I adjust the range and intervals on both axes?

In the example shown, the first issue is the X axis is showing test number values that are not integers; so test value 2.5 does not make any sense and instead, I need to have say 2,4,6,8,10,12, or a grid line at each value from 1 to 12.

For the Y axis, if I wanted a bit more space above and below the points, how can I adjust the scale range from say 0.5 - 2.0 instead of 1.2 - 1.8?

I'm finding the vast array of possible coding a bit dizzying.

enter image description here

Here is the code :

SOH1 %>% ggplot(aes(Test.No.,MJ, color = MJ))
+geom_point(size=3,alpha=0.7)+ geom_smooth(method=lm,se=F) 

Thanks

Julian


Solution

  • This is where you need to use xlim() and ylim() methods.

    For xlim() you need to pass two numeric values, specifying the left and the right values of your desired interval.

    For ylim() you need to pass two numeric values, specifying the lower and the upper values of your desired interval.

    One way is to append these methods to the end of your code :

    SOH1 %>% ggplot(aes(Test.No.,MJ, color = MJ))+
    geom_point(size=3,alpha=0.7)+ geom_smooth(method=lm,se=F)+
    xlim(1,12) + ylim(0.5,2)
    

    Updated Answer :

    If you want to set the breaking number manually, you can use scale_x_continuous() instead of xlim(). You need to pass the desired breaks as an array to this function. for example :

    scale_x_continuous(breaks=c(0,2,4,6,8,10,12))
    

    So after changing the code, it will be like :

    SOH1 %>% ggplot(aes(Test.No.,MJ, color = MJ))+
    geom_point(size=3,alpha=0.7)+ geom_smooth(method=lm,se=F)+
    scale_x_continuous(breaks=c(0,2,4,6,8,10,12)) + ylim(0.5,2)