Search code examples
rggplot2axis-labels

Customise specific x-axis ticks in ggplot2


It sounds easy but I've been searching for a while and got nowhere.

I have this data:

> df <- data.frame(themes = c("Restoration techniques", "Managing projects", "Ecology and hydrology", "Carbon benefits of peatland"), before = c(2.243243, 2.162162, 2.162162, 2.135135), after = c(2.366667, 2.366667, 2.366667, 2.233333))
> df
                       themes   before    after
2      Restoration techniques 2.243243 2.366667
1       Ecology and hydrology 2.162162 2.366667
4 Carbon benefits of peatland 2.162162 2.366667
3           Managing projects 2.135135 2.233333

and I am plotting it this way:

ggplot(df) +
  geom_segment(aes(x = fullname, xend = fullname, y = 1, yend = 3), color = "grey") +
  geom_segment(aes(x = fullname, xend = fullname, y = before, yend = after), color = "yellowgreen") +
  geom_point(aes(x = fullname, y = before), color = viridis(50)[40], size = 4) +
  geom_point(aes(x = fullname, y = after), color = viridis(50)[25], size = 4) +
  coord_flip() +
  theme_ipsum() +
  xlab("") + ylab("")

with the following result:

enter image description here

What I want is to change the ticks' labels on the horizontal axis.

More specifically, I want no numbers and I want to have "Low" where value 1 is, "Medium" where value 2 is, and "High" where value 3 is.

I tried to use scale_x_discrete(), specifically adding:

+
scale_x_discrete(breaks=c(1, 2, 3), labels=c("Low", "Medium", "High"))

but what I get is the following image:

enter image description here

I am getting the feeling that the issue might lie in the nature of the x axis, but I am not getting how should I solve things and what line(s) should I add to the plot's code.


Solution

  • You need to use scale_y_continuous() as follows:

    ggplot(df) +
      geom_segment(aes(x = themes, xend = themes, y = 1, yend = 3), color = "grey") +
      geom_segment(aes(x = themes, xend = themes, y = before, yend = after), color = "yellowgreen") +
      geom_point(aes(x = themes, y = before), color = viridis(50)[40], size = 4) +
      geom_point(aes(x = themes, y = after), color = viridis(50)[25], size = 4) +
      coord_flip() +
      theme_ipsum() +
      xlab("") + ylab("") + 
      scale_y_continuous(breaks=c(1,2,3), labels=c("Low", "Medium", "High"))
    

    enter image description here

    You have to use the scale_ function that matches the nature of the data you have. Since your y-axis data are continuous, you need scale_y_continuous() even though your goal is to make it look as though it's discrete.