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..
Are you looking for the following plot:
@agstudy's answer didn't work for me with the latest version of
ggplot2
, but this did, usingmaggritr
pipes:It works because if
geom_line
sees thatdata
is a function, it will call that function with the inherited version ofdata
and use the output of that function asdata
.Here 2 options for subsetting:
Using
subset
from base R:Using
subset
the argument ofgeom_line
(Note I am usingplyr
package to use the special.
function).You can also use the complementary subsetting:
Try filter to subset only the rows of P1 and P3
Than yo can plot Value1. vs Value2.
There's another solution that I find useful, especially when I want to plot multiple subsets of the same object:
Your formulation is almost correct. You want:
Where the
|
('pipe') means 'or'. Your solution,ID=="P1 & P3"
, is looking for a case where ID is literally"P1 & P3"