在ggplot2中进行切换

时间:2015-07-30 23:49:46

标签: 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,color = V3
  • x = V1,y = V3,颜色= V2
  • x = V2,y = V3,color = V1

如何用ggplot2进行这样的事情?

1 个答案:

答案 0 :(得分:3)

您可以通过将数据放入ggplot喜欢的格式来获得此功能。在这种情况下,可以使用一列来将数据拆分为facets(下面称为var)。为此,我只重复了三次数据,为每个双向组合选择合适的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