在R中创建多个折线图
我有以下虚拟数据在R中创建多个折线图,r,plot,ggplot2,R,Plot,Ggplot2,我有以下虚拟数据 set.seed(45) df <- data.frame(x=rep(1:5, 9), val1=sample(1:100,45), val2=sample(1:100,45),variable=rep(paste0("category",1:9),each=5)) set.seed(45) df我不完全确定你想要什么,但是像这样的东西 ggplot(df, aes(x=val1, y=val2)) + geom_line() + facet_grid(. ~ x)
set.seed(45)
df <- data.frame(x=rep(1:5, 9), val1=sample(1:100,45),
val2=sample(1:100,45),variable=rep(paste0("category",1:9),each=5))
set.seed(45)
df我不完全确定你想要什么,但是像这样的东西
ggplot(df, aes(x=val1, y=val2)) + geom_line() + facet_grid(. ~ x)
使用ggplot2
最好先融化数据
set.seed(45)
## I've renamed your 'variable' to 'cat'
df <- data.frame(x=rep(1:5, 9), val1=sample(1:100,45),
val2=sample(1:100,45),cat=rep(paste0("category",1:9),each=5))
library(ggplot2)
library(reshape2)
df_m <- melt(df, id.var=c("x", "cat"))
ggplot(df_m, aes(x=x, y=value, group=variable)) +
geom_line() +
facet_wrap(~cat)
set.seed(45)
##我已将您的“变量”重命名为“cat”
dfMoreggplot2
选项,无需重塑数据
## All on one
ggplot(df, aes(x, val1, color=variable, linetype="a")) +
geom_line() +
geom_line(aes(x, val2, color=variable, linetype="b")) +
theme_bw() + ylab("val") +
scale_linetype_manual(name="val", labels=c("val1", "val2"), values=1:2)
## Faceted
ggplot(df, aes(x, val1, color=variable, linetype="a")) +
geom_line() +
geom_line(aes(x, val2, color=variable, linetype="b")) +
theme_bw() + ylab("val") +
guides(color=FALSE) +
scale_linetype_manual(name="val", labels=c("val1", "val2"), values=1:2) +
facet_wrap(~variable)