通过独特的配对进行切割

时间:2016-09-14 07:51:00

标签: r ggplot2

我想用ggplot创建一些使用分面的图。我对ggplot来说比较新,所以我正在设置情节。为了测试我设置了一些测试数据。实际数据很大,我想先玩这些玩具箱。这是玩具数据

@NgModule()

我想为所有独特的m1 <- matrix(rep(c("Skin","Human"),100),ncol = 2,byrow = T) m2 <- matrix(rep(c("Head","Animal"),200),ncol = 2, byrow=T) m3 <- matrix(rep(c("Skin","Animal"),250), ncol = 2, byrow=T) y <- rnorm(550,0,1) x1 <- rnorm(100,0,1) x2 <- rnorm(200,0,1) x3 <- rnorm(250,0,1) m1 <- as.data.frame(cbind(x1,m1)) m2 <- as.data.frame(cbind(x2,m2)) m3 <- as.data.frame(cbind(x3,m3)) colnames(m1) <- c("x1","type","class") colnames(m2) <- c("x1","type","class") colnames(m3) <- c("x1","type","class") data <- as.data.frame(cbind(y,rbind(m1,m2,m3))) data <- cbind(data,rnorm(550,0,1)) colnames(data) <- c("y","x1","type","class","x2") data <- data[,c("y","x1","x2","type","class")] plot(sort(data[1:100,"y"]),sort(data[1:100,"x1"]),col="red") points(sort(data[1:100,"y"]),sort(data[1:100,"x2"]),col="blue") 对绘制一个情节,在每个情节中,我会看到c("type","class")x1x2的两个散点图。我认为facetting是正确的方法,但我努力达到预期的效果。

1 个答案:

答案 0 :(得分:2)

根据示例代码生成的图表,您似乎想要在同一个图上绘制两组(x1,y)(x2,y)ggplot能够处理好。但是,ggplot适用于 long 表而不是 wide 表。

我提供了一种达到预期结果的方法。在您的代码块之后可以执行以下步骤以实现所需的结果。

  1. 使用ggplot的内置功能将您的表格从头到尾融为一体。请注意,color参数会自动以不同颜色绘制x1x2

    library(reshape2) # Used to melt the table 
    library(ggplot2) # Used to plot
    data <- melt(data, id.vars = c('type','class','y'), measure.vars = c('x1','x2'))
    head(data)
      # type class          y variable              value
    # 1 Skin Human  1.3170057       x1  -1.09101346133313
    # 2 Skin Human  1.2805021       x1 -0.883308758331181
    # 3 Skin Human -0.7620298       x1 0.0800447346341697
    # 4 Skin Human  0.2766297       x1  0.589741587886533
    # 5 Skin Human -1.8504755       x1 -0.178520217862402
    # 6 Skin Human  0.6474738       x1    0.1039386636512
    
    p1 <- ggplot(data, aes(x = as.numeric(value), y = y, color = variable))
    print(p1)
    

    un-faceted plot

  2. facet_wraptype

    的独特组合使用class分面
    faceted <- p1 + facet_wrap(~type + class)
    print(faceted)
    
  3. output plot