Reputation: 2240
I have the following dummy data.
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))
I would like to plot val1 and val2 based on x (which in my real data is a sequence of date values). How can I accomplish this. I have tried ggplot2, mplot, and plot all without success. I have also looked at the other similar posts but they do not work or address my needs.
Upvotes: 3
Views: 173
Reputation: 32446
More ggplot2
options, without reshaping data
## 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)
Upvotes: 5
Reputation: 8343
Using ggplot2
it's a good idea to melt your data first
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)
Upvotes: 4
Reputation: 1367
I'm not entirely sure what you want, but something like this?
ggplot(df, aes(x=val1, y=val2)) + geom_line() + facet_grid(. ~ x)
Upvotes: 1