子集和 ggplot2 [英] Subset and ggplot2

查看:34
本文介绍了子集和 ggplot2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 ggplot2 绘制数据框的子集时遇到问题.我的 df 就像:

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

df = data.frame(ID = c('P1', 'P1', 'P2', 'P2', 'P3', 'P3'),
                Value1 = c(100, 120, 300, 400, 130, 140),
                Value2 = c(12, 13, 11, 16, 15, 12))

我现在如何仅针对 IDs 'P1' 绘制 Value1Value2'P3'?例如我试过:

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.

推荐答案

这里有 2 个子集选项:

Here 2 options for subsetting:

使用来自基础 R 的 subset:

Using subset from base R:

library(ggplot2)
ggplot(subset(dat,ID %in% c("P1" , "P3"))) + 
         geom_line(aes(Value1, Value2, group=ID, colour=ID))

使用subsetgeom_line的参数(注意我使用plyr包来使用特殊的.函数).

Using subset the argument of geom_line(Note I am using plyr package to use the special . function).

library(plyr)
ggplot(data=dat)+ 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
                ,subset = .(ID %in% c("P1" , "P3")))

您也可以使用补充子集:

You can also use the complementary subsetting:

subset(dat,ID != "P2")

这篇关于子集和 ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆