Search code examples
rggplot2maxaxismin

Is there a way to set the x-axis to min and max value in ggplot?


Data:

Month<-c(jan,feb,mar,apr,may)
Values(10,5,8,12,4)

I was wondering if there is a way to set the x axis to min and max values without hardcoding it. For example instead of hard coding coord_cartesian(ylim = c(4, 12)) is there a way to just assign y axis to max and min so the graph automatically sets the limits at 4 and 12.


Solution

  • We can extract the range from the 'Values' column

    library(ggplot2)
    ggplot(df1, aes(x = Month, y = Values)) + 
         geom_col() + 
         coord_cartesian(ylim = range(df1$Values))
    

    -output

    enter image description here


    If we need to change the tick marks, use scale_y_continuous

    rng_values <- range(df1$Values) -  c(2, 0)
    ggplot(df1, aes(x = Month, y = Values)) + 
         geom_col() + 
         coord_cartesian(ylim = rng_values ) + 
         scale_y_continuous(breaks = do.call(seq, 
            c(as.list(rng_values),
                list(by = 0.5))))
    

    data

    df1 <- data.frame(Month = month.abb[1:5], Values = c(10, 5, 8, 12, 4))