Discrete x axis ticks in ggplot2

ggplot2

#1

I’m trying to illustrate changes over time for two different groups. This is only to illustrate a concept so I don’t want too many things in the graph and therefore only show 4 specific time points on the x axis (Start, n-1, n, End). While I’m happy with the graph in general, I’d like to know how to remove the second tick (without label) on the x axis.

I’ve tried scale_x_discrete(limits = c(…) but couldn’t find a way to remove the second tick. For all other time points on the x axis it is possible to add or remove the tick by adding content between the quotation marks.

Does anyone has suggestions how to fix this or plot something similar using a different approach? Thanks for your help.


# Load packages
library(ggplot2)
library(magrittr)
# Create data
group1_values <- c(25, 20, 19, 14)
group1_title <- c("Group 1", "Group 1", "Group 1", "Group 1")
group2_values  <- c(24.5, 19.5, 9.5, 4)
group2_title <- c("Group 2", "Group 2", "Group 2", "Group 2")
values <- c(group1_values, group2_values)
group <- c(group1_title, group2_title)
time <- c(1, 6, 7, 12, 1, 6, 7, 12)
data <- data.frame(values, group, time)
# Plot data
data %>% 
  ggplot(aes(x = time, y = values, colour = group, shape = group)) +
    stat_summary(fun.y = mean, geom = "point") +
    geom_line(aes(linetype = group)) +
    scale_x_discrete(limits = c("Start", "", "", "", "", "n-1", "n", "", "", "", "", "End")) +
    labs(x = "Time", y = "Value", colour = "", shape = "", linetype = "") +
    theme_classic()


#2

Just use a continuous scale and label appropriately:

data %>% 
  ggplot(aes(x = time, y = values, colour = group, shape = group)) +
    stat_summary(fun.y = mean, geom = "point") +
    geom_line(aes(linetype = group)) +
    scale_x_continuous(breaks = c(1, 6, 7, 12), labels = c("Start", "n-1", "n", "End")) + 
    labs(x = "Time", y = "Value", colour = "", shape = "", linetype = "") +
    theme_classic()

I have no idea where the additional tick came from in your discrete version. Maybe a bug for the developers to look at?


#3

Woohoo, thanks! This works excellent for me now.

I’m new to the RStudio Community, not sure if I need to report this elsewhere so the developers can have a look in case it’s a bug?


#4

No problem.

I’m not sure what the proper method of logging this would be.

@mara, could you please advise?


#5

If you think you’ve found a bug, you should file an issue for the package (in this case, ggplot2) on its GitHub repo. There’s more detail (put more eloquently than I could replicate) on that here: https://www.tidyverse.org/contribute/#issues

If you’re new to GitHub or creating issues, the GH documentation is really helpful (and full of pictures):
https://help.github.com/articles/creating-an-issue/


#6

Thanks for the info, will create an issue on GitHub.