简体   繁体   English

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

[英]Combine continuous and discrete color scale in ggplot2?

I am a ggplot2 newbie. 我是一个ggplot2新手。 I am making a scatter plot where the points are colored based on a third continuous variable. 我正在制作散点图,其中点基于第三个连续变量着色。 However, for some of the points, that continuous variable has either an Inf value or a NaN. 但是,对于某些点,该连续变量具有Inf值或NaN。 How can I generate a continuous scale that has a special, separate color for Inf and another separate color for NaN? 如何为Inf生成具有特殊单独颜色的连续刻度,为NaN生成另一种单独颜色?

One way to get this behavior is to subset the data, and make a separate layer for the special points, where the color is set. 获得此行为的一种方法是对数据进行子集化,并为设置颜色的特殊点创建单独的图层。 But I'd like the special colors to enter the legend as well, and think it would be cleaner to eliminate the need to subset the data. 但我也希望特殊的颜色能够进入传奇,并认为消除数据子集的需要会更加清晰。

Thanks! 谢谢! Uri 乌里

I'm sure this can be made more efficient, but here's one approach. 我相信这可以提高效率,但这是一种方法。 Essentially, we follow your advice of subsetting the data into the different parts, divide the continuous data into discrete bins, then patch everything back together and use a scale of our own choosing. 基本上,我们遵循您的建议,将数据子集化到不同的部分,将连续数据划分为离散的箱,然后将所有内容重新组合在一起并使用我们自己选择的比例。

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)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM