在R中多面ggplot2图的边距内按因数着色点 [英] Colouring points by factor within the margin of a faceted ggplot2 plot in R

查看:164
本文介绍了在R中多面ggplot2图的边距内按因数着色点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to create a faceted plot with margins in ggplot2. However, I'd like the margin plot to have colours according to from which facet the particular point has been derived. It's probably best illustrated with an example:

library(ggplot2)

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

在标记为(all)"的边距图中,我希望将"gear = 3"的点用一种颜色绘制,将"gear = 4"的点用另一种颜色绘制,并将"gear"的那些点进行绘制. = 5和第三个.

Within the margin plot labelled as "(all)", I want those dots that have "gear = 3" to be plotted with one colour, those with "gear = 4" with a second colour, and those with "gear = 5" with a third one.

此人无法完成工作:

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

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

Is there a way to achieve what I want?

推荐答案

如何创建一个新变量作为参考并以此标记点颜色?如果您也不介意前三个方面也被着色,这些点似乎可以正常工作.

How about creating a new variable as a reference and colour the points by that? Seems to work provided you don't mind the points in the first 3 facets being coloured too.

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个方面删除了色键,但并非没有处理原始数据;

I have managed to get it to remove the colour key from the first 3 facets but not without playing around with the original data;

复制原始数据(每个记录有2个),然后使用冗余记录而不是使用边距图来生成所有"构面.

Duplicate the original data (so there are 2 of each record) then instead of using a margin plot to produce the "all" facet, using the redundant records instead.

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)

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

I'm not sure that's the best way to go about it but perhaps someone with more expertise might be able to advise?

这篇关于在R中多面ggplot2图的边距内按因数着色点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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