ggplot2:根据某些条件将data.frame分组在构面中 [英] ggplot2: group data.frame in facets according to some criteria

查看:92
本文介绍了ggplot2:根据某些条件将data.frame分组在构面中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的data.frame包含要绘制的数据,那么在facet_wrap(或facet_grid)的不同图中将数据分组"的最简单方法是什么?

If I have a data.frame containing the data I want to plot, what is the easiest way to "group" data in the different plots of a facet_wrap (or facet_grid) ?

举一个具体的例子,如果数据框是这样的:

To make a concrete example, if the data frame is like:

ID | P1 | P2 | P3 | P4 | P5
....(data)....

我希望在第一个方面具有ID的P1,P2,P3,在第二个方面具有ID的P4,在第三个方面具有P5的ID.

I would like to have P1,P2,P3 over ID in the first facet, P4 over ID in the second and P5 over ID in the third.

推荐答案

我怀疑我举了一个完全模仿您的示例,但希望您能明白这一点. ggplot2图形的技巧是使用melt()将数据放入长格式.然后,您可以根据想要对它们进行分组的方式创建一个facet ing变量.这是一个示例:

I doubt I made an example that exactly mimics yours, but hopefully you'll get the point. The trick to ggplot2 graphics is to put your data into long format with melt(). Then you can create a faceting variable according to how you want to group them. Here's an example:

library(ggplot2)
dat <- data.frame(ID = rnorm(10), P1 = rnorm(10), P2 = rnorm(10), P3 = rnorm(10), P4 = rnorm(10), P5 = rnorm(10)) 
dat.m <- melt(dat, id.vars = 1)
#Create faceting variable
dat.m <- transform(dat.m, facet = ifelse(variable %in% c("P1", "P2", "P3"), 1, ifelse(variable == "P4", 2,3)))

ggplot(dat.m, aes(ID, value)) + geom_point() + facet_wrap(~facet)

这篇关于ggplot2:根据某些条件将data.frame分组在构面中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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