我是ggplot2的新手但尝试使用它。我有两个变量:SA(4级:0,1000,2000和3000)和GA(4级:0,0.5,1和2)。我想用SA分组这些(如图)
> G<- read.table("k.csv", sep=";",header = TRUE)
> G
SA GA PH
1 0 0.0 41
2 0 0.0 27
3 0 0.0 28
4 0 0.0 25
5 0 0.5 35
6 0 0.5 45
7 0 0.5 35
8 0 0.5 55
9 0 1.0 45
10 0 1.0 35
11 0 1.0 38
12 0 1.0 46
13 0 2.0 52
14 0 2.0 40
15 0 2.0 40
16 0 2.0 35
17 1000 0.0 30
18 1000 0.0 30
19 1000 0.0 30
20 1000 0.0 30
21 1000 0.5 28
22 1000 0.5 33
23 1000 0.5 31
24 1000 0.5 42
25 1000 1.0 38
26 1000 1.0 30
27 1000 1.0 27
28 1000 1.0 25
29 1000 2.0 30
30 1000 2.0 22
31 1000 2.0 31
32 1000 2.0 44
33 2000 0.0 18
34 2000 0.0 25
35 2000 0.0 24
36 2000 0.0 31
37 2000 0.5 24
38 2000 0.5 22
39 2000 0.5 36
40 2000 0.5 40
41 2000 1.0 27
42 2000 1.0 29
43 2000 1.0 42
44 2000 1.0 33
45 2000 2.0 20
46 2000 2.0 40
47 2000 2.0 30
48 2000 2.0 25
49 3000 0.0 0
50 3000 0.0 0
51 3000 0.0 0
52 3000 0.0 0
53 3000 0.5 24
54 3000 0.5 20
55 3000 0.5 25
56 3000 0.5 NA
57 3000 1.0 37
58 3000 1.0 NA
59 3000 1.0 38
60 3000 1.0 25
61 3000 2.0 24
62 3000 2.0 15
63 3000 2.0 20
64 3000 2.0 32
> ggplot(G, aes(x=SA, y=PH, fill=factor(GA))) +
stat_summary(geom="bar",positiGon=position_dodge(1))
另外,我想在栏中添加错误栏。 有什么想法吗?
答案 0 :(得分:2)
使用data.table
计算标准误差和平均值的解决方案。
library(data.table)
library(ggplot2)
setDT(G)
pd <- G[, .(SE = sd(PH, na.rm = TRUE) / sqrt(.N),
MN = mean(PH, na.rm = TRUE)),
.(SA, GA)]
ggplot(pd, aes(factor(SA), fill = factor(GA))) +
geom_bar(aes(y = MN),
stat = "identity", position = "dodge") +
geom_errorbar(aes(ymin = MN - SE, ymax = MN + SE),
position = "dodge") +
labs(x = "SA",
y = "PH",
fill = "GA") +
theme_classic()
答案 1 :(得分:1)
library(tidyr)
std.error <- function(x) sd(x)/sqrt(length(x))
means <- function(x)mean(x, na.rm=TRUE)
df2 <- G %>%
group_by(SA, GA) %>%
mutate(error=std.error(PH)) %>%
summarise_at(vars(PH:error), funs(means))
ggplot(df2, aes(as.factor(SA), PH, fill=as.factor(GA))) +
geom_bar(stat="identity", position="dodge") +
geom_errorbar(aes(ymin=PH-error, ymax=PH+error),
width=.2, position=position_dodge(.9))