我进行了六次治疗的实验,每次治疗都在光明和黑暗中进行.我用ggplot2来制作条形图.我想将重要性字母(例如LSD结果)添加到图表中以显示每种处理的亮度和暗度之间的差异,但它给我一个错误.有什么建议吗?
data <- read.table(header = TRUE, text =
'T0 T1 T2 T3 T4 T5 LVD
40 62 50 45 45 58 Light
30 60 44 40 30 58 Light
30 68 42 35 32 59 Light
47 75 58 55 50 70 Dark
45 75 52 54 42 78 Dark
50 75 68 48 56 75 Dark
')
gla <- melt(data,id="LVD")
ggplot(gla, aes(x=variable, y=value, fill=as.factor(LVD))) +
stat_summary(fun.y=mean,
geom="bar",position=position_dodge(),colour="black",width=.7,size=.7) +
stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
color="black",position=position_dodge(.7), width=.2) +
scale_fill_manual("Legend", values = c("Light" = "white", "Dark" ="gray46")) +
xlab("Treatments")+
ylab("Germination % ") +
theme(panel.background = element_rect(fill = 'white', colour = 'black'))
Run Code Online (Sandbox Code Playgroud)
到这里它完全有效,但是当我使用geom_text时它会出错
+ geom_text(aes(label=c("a","b","a","a","a","a, a","b","a","b","a","b")))
Run Code Online (Sandbox Code Playgroud)
错误是:
Error: Aesthetics must be either length 1 or the same as the data (36): label, x, y, fill
Run Code Online (Sandbox Code Playgroud)
问题是你有36个数据点,你总结为12. ggplot只允许映射到36个数据点geom_text(错误告诉你).为了使用汇总的12个点,您需要stat_summary再次使用.
基本规则是统计变换(如摘要)不在层之间传递*(即geoms和stats).因此geom_text不知道y原始stat_summary实际计算的值是什么.
然后你还需要修复你的信中的拼写错误.
我们最终得到:
ggplot(gla, aes(x=variable, y=value, fill=as.factor(LVD))) +
stat_summary(fun.y=mean,
geom="bar",position=position_dodge(),colour="black",width=.7,size=.7) +
stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
color="black",position=position_dodge(.7), width=.2) +
stat_summary(geom = 'text', fun.y = max, position = position_dodge(.7),
label = c("a","b","a","a","a","a", "a","b","a","b","a","b"), vjust = -0.5) +
scale_fill_manual("Legend", values = c("Light" = "white", "Dark" ="gray46")) +
xlab("Treatments") +
ylab("Germination % ") +
scale_y_continuous(expand = c(0, 0), limits = c(0, 85)) +
theme_bw()
Run Code Online (Sandbox Code Playgroud)
我不喜欢炸药图,所以这是我的版本:
let <- c("a","b","a","a","a","a", "a","b","a","b","a","b")
stars <- ifelse(let[c(TRUE, FALSE)] == let[c(FALSE, TRUE)], '', '*')
ggplot(gla, aes(x = variable, y = value)) +
stat_summary(aes(col = as.factor(LVD)),
fun.y=mean, fun.ymin = min, fun.ymax = max,
position = position_dodge(.3), size = .7) +
stat_summary(geom = 'text', fun.y = max, position = position_dodge(.3),
label = stars, vjust = 0, size = 6) +
scale_color_manual("Legend", values = c("Light" = "black", "Dark" ="gray46")) +
xlab("Treatments") +
ylab("Germination % ") +
scale_y_continuous(expand = c(0.1, 0)) +
theme_bw()
Run Code Online (Sandbox Code Playgroud)