我有这个数据框:
d <- data.frame(c(rep("A",5), rep("B",5), rep("C",5), rep("D",5), rep("E",5)),
sample(c(1:25), 25, replace=TRUE),
sample(c(1:25), 25, replace=TRUE))
colnames(d) <- c("col1","col2","col3")
head(d);tail(d)
col1 col2 col3
1 A 20 13
2 A 24 21
3 A 9 23
4 A 13 1
5 A 14 12
6 B 22 5
col1 col2 col3
20 D 23 1
21 E 3 1
22 E 24 19
23 E 15 3
24 E 22 6
25 E 21 7
我想使用GGPLOT分别绘制图形。由于我有五个字母,我将有五个线图形。 col1的每个字母给我一个图形,其中col2和col3在同一行图中。
例如:
第一张图片将包含x=A
和y= col1 and col 3
。其他字母也一样。
我该怎么做?
答案 0 :(得分:2)
library(ggplot2)
library(gridExtra)
d$V1 <- paste(d$col1,1:5, sep='')
da <- d %>% filter(col1 == "A")
db <- d %>% filter(col1 == "B")
dc <- d %>% filter(col1 == "C")
dd <- d %>% filter(col1 == "D")
de <- d %>% filter(col1 == "E")
#
A <- ggplot(data=da, aes(x=V1, y=col2, group=1)) + geom_point(stat='summary', fun.y=sum, size=0) + stat_summary(fun.y=sum, geom="line") + geom_line(data=da, aes(x=V1, y=col3), color="red") + theme_bw()
B<- ggplot(data=db, aes(x=V1, y=col2, group=1)) + geom_point(stat='summary', fun.y=sum, size=0) + stat_summary(fun.y=sum, geom="line") + geom_line(data=db, aes(x=V1, y=col3), color="red") + theme_bw()
C<- ggplot(data=dc, aes(x=V1, y=col2, group=1)) + geom_point(stat='summary', fun.y=sum, size=0) + stat_summary(fun.y=sum, geom="line") + geom_line(data=dc, aes(x=V1, y=col3), color="red") + theme_bw()
D<- ggplot(data=dd, aes(x=V1, y=col2, group=1)) + geom_point(stat='summary', fun.y=sum, size=0) + stat_summary(fun.y=sum, geom="line") + geom_line(data=dd, aes(x=V1, y=col3), color="red") + theme_bw()
E <- ggplot(data=de, aes(x=V1, y=col2, group=1)) + geom_point(stat='summary', fun.y=sum, size=0) + stat_summary(fun.y=sum, geom="line") + geom_line(data=de, aes(x=V1, y=col3), color="red") + theme_bw()
grid.arrange(A, B, C, D, E, ncol=5)