嗨,我有如下数据:
共 38 列。治疗列中的 10 种治疗类型和日期列数据示例代码中从 25-29 的日期(例如 2 种治疗类型但数据有 10 种类型):
df <- structure(
list(
Christensenellaceae = c(
0,
0.009910731,
0.010131195,
0.009679938,
0.01147601,
0.010484508,
0.008641566,
0.010017172,
0.010741488,
0.1,
0.2,
0.3,
0.4),
Date=c(25,25,25,25,25,27,27,27,27,27,27,27,27),
Treatment = c(
"Original Sample",
"Original Sample",
"Original Sample",
"Original Sample",
"Original Sample"
"Treatment 1",
"Treatment 1",
"Treatment 1",
"Treatment 1",
"Treatment 2",
"Treatment 2",
"Treatment 2",
"Treatment 2")
),class = "data.frame",
row.names = c(NA,-9L)
)
我想做的是为每一列创建2个图,一个用于原始治疗,另一个用于此处的示例(1-2)中的所有治疗类型(1-10),并根据每种治疗类型添加观察的平均线. 治疗图总共应该有 10 条平均线(这里是 2 条)。遗憾的是,我不明白如何添加按治疗类型分组的行,这是我基于所有治疗类型的一行代码。如何添加按治疗类型分组的行:
df_3 %>%
pivot_longer(-treatment) %>%
mutate(plot = ifelse(str_detect(treatment, "Original"),
"Original sample",
"Treatment"),
treatment = str_extract(treatment, "\\d+$")) %>%
group_by(name) %>%
group_split() %>%
map(~.x %>% ggplot(aes(x = factor(treatment), y = value, color = factor(name))) +
geom_point() +
stat_summary(aes(y = value,group=1), fun.y=mean, colour="red", geom="line",group=1)
+
facet_wrap(~plot, scales = "free_x") +
labs(x = "Treatment", y = "Value", color = "Taxa") +
guides(x = guide_axis(angle = 90))+
theme_bw())
如您所见,平均线只有一条,每种治疗类型都需要 10 条(此处为 2 条)。有什么方法可以编辑我的代码以便它可以工作吗?谢谢你:)
我也试过这段代码,但我似乎没有工作
df %>%
pivot_longer(-c(Treatment, Date), names_to = "taxon")
%>% mutate( type = Treatment %>% str_detect("Original")
%>% ifelse("Original", "Treatment"), treatment_nr = Treatment
%>% str_extract("(?<=Treatment )[0-9]+") )
%>% ggplot(aes(Date, value, color = treatment_nr)) +
geom_point() + stat_summary( geom = "point", fun.y =
"mean", size = 3, shape = 24 ) + geom_line() + facet_grid(type
~ taxon, scales = "free_y") #> Warning: `fun.y` is deprecated.
Use `fun` instead.