首页 文章

在ggplot2中结合连续和离散色标?

提问于
浏览
10

我是一个ggplot2新手 . 我正在制作散点图,其中点基于第三个连续变量着色 . 但是,对于某些点,该连续变量具有Inf值或NaN . 如何为Inf生成具有特殊单独颜色的连续刻度,为NaN生成另一种单独颜色?

获得此行为的一种方法是对数据进行子集化,并为设置颜色的特殊点创建单独的图层 . 但我也希望特殊颜色能够进入传奇,并认为消除数据子集的需要会更加清晰 .

谢谢!乌里

1 回答

  • 12

    我相信这可以提高效率,但这是一种方法 . 基本上,我们遵循您的建议,将数据子集化到不同的部分,将连续数据划分为离散的箱,然后将所有内容重新组合在一起并使用我们自己选择的比例 .

    library(ggplot2)
    library(RColorBrewer)
    
    #Sample data
    dat <- data.frame(x = rnorm(100), y = rnorm(100), z = rnorm(100))
    dat[sample(nrow(dat), 5), 3] <- NA
    dat[sample(nrow(dat), 5), 3] <- Inf
    
    #Subset out the real values
    dat.good <- dat[!(is.na(dat$z)) & is.finite(dat$z) ,]
    #Create 6 breaks for them
    dat.good$col <- cut(dat.good$z, 6)
    
    #Grab the bad ones
    dat.bad <- dat[is.na(dat$z) | is.infinite(dat$z) ,]
    dat.bad$col <- as.character(dat.bad$z)
    
    #Rbind them back together
    dat.plot <- rbind(dat.good, dat.bad)
    
    #Make your own scale with RColorBrewer
    yourScale <- c(brewer.pal(6, "Blues"), "red","green")
    
    ggplot(dat.plot, aes(x,y, colour = col)) + 
      geom_point() +
      scale_colour_manual("Intensity", values = yourScale)
    

    enter image description here

相关问题