Search code examples
raxis-labelsgraphing

Making X-axis labels in R more granular


I'm producing a graph and R and would like the x axis to be more granular.

  Tenure         Type Visits Members   Percent
1      0        Basic 122446  283975 0.4311858
2      0      Premium  21190   44392 0.4773383
3      1        Basic  92233  283975 0.3247927
4      1      Premium  17909   44392 0.4034285
5      2        Basic  42516  283975 0.1497174
6      2      Premium   9613   44392 0.2165480


 plot(Visit_Curve$Tenure, Visit_Curve$Percent, type = "n", main = "Visit Curve")
    lines(Visit_Curve$Tenure[Visit_Curve$Type == "Basic"], Visit_Curve$Percent[Visit_Curve$Type == "Basic"], col = "red")
    lines(Visit_Curve$Tenure[Visit_Curve$Type == "Premium"], Visit_Curve$Percent[Visit_Curve$Type == "Premium"], col = "blue")

The code above produces a chart that has the x-axis broken down by factors of 50. Is there a way to easily customize the scale in base R plotting? Perhaps have a tick every 10 or 5?

Thanks, Ben


Solution

  • Just make custom axes with axes = FALSE and ?axis

    You can clean up your code substantially:

    Visit_Curve <- read.table(header = TRUE, text = "Tenure         Type Visits Members   Percent
    1      0        Basic 122446  283975 0.4311858
    2      0      Premium  21190   44392 0.4773383
    3      1        Basic  92233  283975 0.3247927
    4      1      Premium  17909   44392 0.4034285
    5      2        Basic  42516  283975 0.1497174
    6      2      Premium   9613   44392 0.2165480")
    
    with(Visit_Curve, {
      plot(Tenure, Percent, type = 'n', main = 'Visit Curve', axes = FALSE)
      axis(1, at = seq(0, 2, by = .15))
      axis(2, at = seq(.15, .45, by = .05), las = 1)
      box('plot')
      lines(Tenure[Type == 'Basic'], Percent[Type == 'Basic'], col = 'red')
      lines(Tenure[Type == 'Premium'], Percent[Type == 'Premium'], col = 'blue')
    })
    

    or individually suppress the labels on each axis with xaxt = 'n' or yaxt = 'n'

    with(Visit_Curve, {
      plot(Tenure, Percent, type = 'n', main = 'Visit Curve', xaxt = 'n', las = 1)
      axis(1, at = seq(0, 2, by = .15))
      lines(Tenure[Type == 'Basic'], Percent[Type == 'Basic'], col = 'red')
      lines(Tenure[Type == 'Premium'], Percent[Type == 'Premium'], col = 'blue')
    })
    

    enter image description here

    Or using ggplot2

    library('ggplot2')
    ggplot(Visit_Curve, aes(Tenure, Percent, colour = Type)) +
      geom_line() +
      scale_x_continuous(breaks = seq(0, 2, .15)) + 
      labs(title = 'Visit Curve')
    

    enter image description here