0
votes

I make a scatter plot and fit a line on it; now I need to change the tick-level labels of my x-axis, which is continuous. The data:

y <- data.frame(a = 1:5, b = 5:9)
> y
  a b
1 1 5
2 2 6
3 3 7
4 4 8
5 5 9

And I plot it:

   ggplot(y, aes(a, b))+
      geom_jitter()+
      stat_summary(fun.data = mean_cl_normal)+
      geom_smooth(method = 'lm', formula = y~x)

enter image description here

This is not bad, but I need to change the labels at the x-axis tick level, to make them meaningful, so I try with this:

ggplot(y, aes(a, b))+
  geom_jitter()+
  stat_summary(fun.data = mean_cl_normal)+
  geom_smooth(method = 'lm', formula = y~x)+
  scale_x_discrete("A_Variable", c("a","b","c","d","f"))

enter image description here

It doesn't work. I learn from another SO question that I need to change the x variable to factor, but when I do this, I lose my geom_smooth line. How do I change the tick-level labels of my x-axis without losing my geom_smooth stats?

1

1 Answers

2
votes

You have to use the scale_x_continuous, since your a is a continuous variable. In order to define names for the breaks, you can use the labels parameter.

data.frame(a = 1:5, b = 5:9) %>%
    ggplot(aes(a, b))+
    geom_jitter()+
    stat_summary(fun.data = mean_cl_normal)+
    geom_smooth(method = 'lm', formula = y~x)+
    scale_x_continuous(breaks=1:5, labels=c("a", "b", "c", "d", "f")) +
    labs(x="A_Variable", y="B_Variable", title="A plot")

enter image description here