lila
lila

Reputation: 11

ggplot2 geom_smooth didn't work

I'm plotting two different variables on the same plot. sex_female is chr, including 0 and 1. epoch_36:epoch_144 are num, time variables. Here is my code:

total %>%
select(sex_female, epoch_36:epoch_144)%>%
gather(key = time, value = ac, epoch_36:epoch_144) %>%
group_by(sex_female,time) %>%
mutate(mean = mean(ac)) %>%
ggplot(aes(x = time, y = mean,color = sex_female)) +
geom_point(alpha = .3)+
geom_smooth(method = "lm")+
theme(axis.text.x = element_text(angle = 90,hjust = 1))

After the mutation, I got the tibble:

A tibble: 45,780 x 4
# Groups:   sex_female, time [218]
sex_female     time    ac     mean
    <chr>    <chr> <dbl>    <dbl>
1          1 epoch_36  49.8 54.96406
2          0 epoch_36  34.7 55.43448
3          0 epoch_36  70.9 55.43448
4          0 epoch_36  12.3 55.43448
5          1 epoch_36 102.7 54.96406
6          1 epoch_36  77.9 54.96406
7          0 epoch_36   1.1 55.43448
8          1 epoch_36 140.0 54.96406
9          1 epoch_36  51.3 54.96406
10          0 epoch_36   0.0 55.43448
# ... with 45,770 more rows

I've tried using the solution suggested in a similar question: Plot dashed regression line with geom_smooth in ggplot2, but no lines showed up. How do I fix my code to produce lines?

enter image description here

Upvotes: 1

Views: 367

Answers (1)

pogibas
pogibas

Reputation: 28339

Your time column is categorical and you should transform it into numerical.

mutTibble$time <- as.numeric(mutTibble$time)

And for plotting you can use this:

library(ggplot2)
ggplot(mutTibble,
       aes(time, mean, color = factor(sex_female))) +
    geom_point(alpha = 0.3)+
    geom_smooth(method = "lm")+
    theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
    labs(x = "Time",
         y = "Mean"
         color = "Gender (female)")

Upvotes: 1

Related Questions