8

我想在 ggplot2 中创建一个带有边距的多面图。但是,我希望边距图具有根据特定点从哪个方面派生的颜色。最好用一个例子来说明:

library(ggplot2)

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p + facet_grid(.~gear, margins = TRUE)

在标记为“(全部)”的边距图中,我希望那些具有“gear = 3”的点用一种颜色绘制,那些具有“gear = 4”的点用第二种颜色绘制,而那些具有“gear = 5”的点与第三个。

这个不做这项工作:

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(col=gear))
p + facet_grid(.~gear, margins = TRUE)

有没有办法实现我想要的?

4

2 回答 2

3

如何创建一个新变量作为参考并以此为点着色?如果您不介意前 3 个方面的点也被着色,似乎可以工作。

mtcars$ref <- as.factor(mtcars$gear)

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(col=as.factor(gear)))
p + facet_grid(.~ref, margins = TRUE)

由齿轮着色的所有点

编辑:我已经设法让它从前 3 个方面删除颜色键,但不是不玩原始数据;

复制原始数据(因此每条记录有 2 个),然后使用冗余记录而不是使用边距图来生成“全部”方面。

library(ggplot2)

mtcars$ref <- (mtcars$gear)

# create the duplicate
dat <- do.call("rbind", replicate(2, mtcars, simplify = FALSE)) 

# give the duplicates a false value for "gear" so they can be plotted together 
#This value can then be used for faceting, grouping everything with "all".

dat$ref[1:32] <- "all" 


# where not in the "all" facet, change "gear" to one (so they are plotted with the same colour)
dat$gear[dat$ref != "all"] <- 1

# then plot using ref as the facet and gear to colour points.

p <- ggplot(dat, aes(mpg, wt)) + geom_point(aes(col=as.factor(gear)))
p + facet_grid(.~ref, margins = F)

点仅由最终面中的齿轮着色

我不确定这是最好的方法,但也许有更多专业知识的人可以提供建议?

于 2013-05-06T12:41:54.013 回答
1

另一种选择是分别创建多面图和边距图并使用gridExtra库将它们组合起来:

library(ggplot2)
library(gridExtra)
mtcars$ALL <- "all"
p <- ggplot(mtcars, aes(mpg, wt))
p1 <- p + geom_point() + facet_grid(.~gear)
p2 <- p + geom_point(aes(color=factor(gear))) + facet_grid(.~ALL)
grid.arrange(p1, p2, ncol=2)

在此处输入图像描述

于 2013-05-06T14:58:58.693 回答