简体   繁体   中英

Create multiple 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 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.

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)

在此处输入图片说明

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)

刻面

我不完全确定你想要什么,但像这样的东西?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM