ggplot2 geom_smooth没有用

时间:2017-10-22 07:34:50

标签: r ggplot2

我在同一个地块上绘制了两个不同的变量。 sex_female是chr,包括0和1。 epoch_36:epoch_144是num,时间变量。 这是我的代码:

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))

在突变之后,我得到了骰子:

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

我尝试过使用类似问题中建议的解决方案:在ggplot2中使用geom_smooth绘制虚线回归线,但没有显示任何行。如何修复代码以生成行?

enter image description here

1 个答案:

答案 0 :(得分:1)

您的time列是分类的,您应该将其转换为数字。

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

对于绘图,你可以使用它:

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)")