Create mulitple line chart in R

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 do this. I tried ggplot2, mplot and all started talking without success. I also looked at other similar posts but they don't work or do not suit my needs.

Thank.

+3


source to share


3 answers


Additional parameters ggplot2

without changing 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)

      

enter image description here



## 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)

      

enter image description here

+5


source


When using ggplot2

, it is recommended 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)

      



facet

+3


source


I'm not really sure what you want, but something like this?

ggplot(df, aes(x=val1, y=val2)) + geom_line() + facet_grid(. ~ x)

      

+1


source







All Articles