r - ggplot2 中的分面

标签 r ggplot2 facet

我有这个数据集:https://dl.dropboxusercontent.com/u/73950/data.csv 该数据集包含 3 个变量。

以下是我现在可视化数据的方式:

library(ggplot2)
library(reshape2)
library(RColorBrewer)

dat = read.csv("data.csv", header = FALSE)

myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))
sc <- scale_colour_gradientn(colours = myPalette(100))

ggplot(dat, aes(x=V1, y=V3, colour = V2))+ geom_point(alpha = .2,size = 3) + sc

我不想只显示一个图形,而是希望对图形进行分面以显示 3 种不同的方式来将变量归因于每个轴和颜色。因此:

  • x = V1,y = V2,颜色 = V3
  • x = V1,y = V3,颜色 = V2
  • x = V2,y = V3,颜色 = V1

如何使用 ggplot2 的分面来做这种事情?

最佳答案

您可以通过以 ggplot 喜欢的格式放置数据来获得此结果。在本例中,可以使用一个列将数据拆分为多个方面(下面称为 var)。为此,我只需重复数据三次,为每个 2 路组合选择适当的 x 和 y 变量,并使用每个组合中留下的变量作为着色变量。

## Rearrange the data by 2-way combinations, the coloring is the remaining column
res <- do.call(rbind, combn(1:3, 2, function(ii)
    cbind(setNames(dat[,c(ii, setdiff(1:3, ii))], c("x", "y", "color")),
                   var=paste(ii, collapse=".")), simplify=F))

ggplot(res, aes(x=x, y=y, color=color))+ geom_point(alpha = .2,size = 3) + 
  facet_wrap(~ var, scales="free") + sc

enter image description here

关于r - ggplot2 中的分面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31735920/

相关文章:

r - 在 R 中使用 facet_grid 单独突出显示数据

hash - 过滤 Redis 哈希条目

r - 在 dplyr 中对新分配的变量执行操作的最佳方法是什么?

r - 当 `methods` 失败时,如何判断函数调用正在使用什么方法?

r - 如何在ggplot2中为hline添加图例

r - 如何在 RMarkdown 中将 SVG 设置为默认渲染?

r - 使用 ggplot2 绘图 : "Error: Discrete value supplied to continuous scale" on categorical y-axis

mongodb - 如何在 mongodb 中使用 facet 操作查找字段的不同值

r - 根据R中另一个向量中定义的数字位置查找向量的元素

r - Semi_join 根据多个 Y 列过滤 X 的列