Subset and ggplot2

2020-01-24 11:40发布

I have a problem to plot a subset of a data frame with ggplot2. My df is like:

ID Value1 Value2
P1 100 12
P1 120 13
...
P2 300 11
P2 400 16
...
P3 130 15
P3 140 12
...

How can I now plot Value1 vs Value2 only for IDs P1 and P3? For example I tried:

ggplot(subset(df,ID=="P1 & P3") + geom_line(aes(Value1, Value2, group=ID, colour=ID)))

but I always receive an error.

p.s. I also tried many combination with P1 & P3 but I always failed..

标签: r ggplot2 subset
8条回答
迷人小祖宗
2楼-- · 2020-01-24 12:23

Use subset within ggplot

ggplot(data = subset(df, ID == "P1" | ID == "P2") + aes(Value1, Value2, group=ID, colour=ID) + geom_line()

查看更多
Bombasti
3楼-- · 2020-01-24 12:29

With option 2 in @agstudy's answer now deprecated, defining data with a function can be handy.

library(plyr)
ggplot(data=dat) + 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
            data=function(x){x$ID %in% c("P1", "P3"))

This approach comes in handy if you wish to reuse a dataset in the same plot, e.g. you don't want to specify a new column in the data.frame, or you want to explicitly plot one dataset in a layer above the other.:

library(plyr)
ggplot(data=dat, aes(Value1, Value2, group=ID, colour=ID)) + 
  geom_line(data=function(x){x[!x$ID %in% c("P1", "P3"), ]}, alpha=0.5) +
  geom_line(data=function(x){x[x$ID %in% c("P1", "P3"), ]})
查看更多
登录 后发表回答