在ggplot2中结合连续和离散的色阶? [英] Combine continuous and discrete color scale in ggplot2?

查看:520
本文介绍了在ggplot2中结合连续和离散的色阶?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ggplot2新手。我正在绘制散点图,点基于第三个连续变量着色。但是,对于某些点,该连续变量具有Inf值或NaN。我怎样才能产生一个连续的尺度,这个连续的尺度有一个特殊的,分别为Inf的颜色和NaN的另一种颜色?



获得这种行为的一种方法是数据的子集,并为设置颜色的特殊点创建单独的图层。但我希望特殊的颜色也可以进入图例,并且认为消除数据子集的需求会更加清晰。

谢谢!
Uri

解决方案

我相信这可以提高效率,但这里有一种方法。从本质上讲,我们按照您的建议将数据分成不同的部分,将连续数据分成不同的部分,然后将所有部分重新拼凑起来,并使用我们自己选择的比例。

<

$示例数据
dat< - data.frame(x = rnorm($) 100),y = rnorm(100),z = rnorm(100))
dat [sample(nrow(dat),5),3] < - NA
dat [sample(nrow ),5),3]< - Inf

#Subset out real value
dat.good< - dat [!(is.na(dat $ z))& is.finite(dat $ z),]
#为他们创建6个中断
dat.good $ col < - cut(dat.good $ z,6)

#抓住坏人
dat.bad< - dat [is.na(dat $ z)| is.infinite(dat $ z),]
dat.bad $ col< - as.character(dat.bad $ z)

#将它们放回在一起
dat .plot< - rbind(dat.good,dat.bad)

#使用RColorBrewer自定义比例
yourScale< - c(brewer.pal(6,Blues)) ,red,green)

ggplot(dat.plot,aes(x,y,color = col))+
geom_point()+
scale_colour_manual( Intensity,values = yourScale)


I am a ggplot2 newbie. 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. How can I generate a continuous scale that has a special, separate color for Inf and another separate color for 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)

这篇关于在ggplot2中结合连续和离散的色阶?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆