我有一个看起来像这样的 DF
df<-structure(list(treatment = c(0, 0, 1, 1), year = c(2002, 2006,
2002, 2006), avg = c(1.41427998341858, 1.48990147417549, 1.37854380583991,
1.44826789361515)), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -4L), groups = structure(list(
treatment = c(0, 1), .rows = structure(list(1:2, 3:4), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L), .drop = TRUE))
df
treatment year avg
<dbl> <dbl> <dbl>
1 0 2002 1.41
2 0 2006 1.49
3 1 2002 1.38
4 1 2006 1.45
我想创建一个按年份平均的散点图,用不同颜色的线进行处理。
我尝试过使用这种方法,但它给了我一个错误并且只显示点。
geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
ggplot(df,aes(x=as.character(year),y=avg,colour=as.character(treatment)))+
geom_point()+
geom_line()
我看到之前的帖子建议使用
group=1
,但不幸的是,它不起作用。
这是由以下命令生成的图。我希望治疗组能够划出界限。
ggplot(df,aes(x=as.character(year),y=avg,colour=as.character(treatment),group=1))+
geom_point()+
geom_line()
您可以添加相同的颜色参数作为分组参数以获得两条不同的线。由于您只想使用它来强制年份和治疗变量作为离散(非连续)度量,因此将它们转换为字符或因子并不重要(对两者都适用)。
ggplot(df, aes(as.character(year), avg,
group=as.character(treatment),
colour=as.character(treatment))) +
geom_line() +
geom_point()
#same example with factor instead of character
ggplot(df, aes(factor(year), avg,
group=factor(treatment),
colour=factor(treatment))) +
geom_line() +
geom_point()