将ggplot2色标连续缩放的最简单方法是什么?

时间:2013-07-18 02:20:53

标签: r plot ggplot2 heatmap

假设我有这个情节:

ggplot(iris) + geom_point(aes(x=Sepal.Width, y=Sepal.Length, colour=Sepal.Length)) + scale_colour_gradient()

将色标进行离散化的正确方法是什么,例如下面接受的答案(gradient breaks in a ggplot stat_bin2d plot)下面显示的图表?

ggplot正确识别离散值,并为这些使用离散比例,但我的问题是,如果你有连续数据,并且你想要一个离散的颜色条(每个方格对应一个值,方块仍然以渐变着色) ,最好的方法是什么?离散/分箱是否应该发生在ggplot之外并作为单独的离散值列放入数据帧中,或者是否有办法在ggplot中进行?我正在寻找的一个例子类似于此处显示的比例: enter image description here

除了我正在绘制散点图而不是geom_tile / heatmap。

感谢。

2 个答案:

答案 0 :(得分:10)

解决方案稍微复杂一些,因为您需要一个离散的比例。否则你可以简单地使用round

library(ggplot2)

bincol <- function(x,low,medium,high) {
  breaks <- function(x) pretty(range(x), n = nclass.Sturges(x), min.n = 1)

  colfunc <- colorRampPalette(c(low, medium, high))

  binned <- cut(x,breaks(x))

  res <- colfunc(length(unique(binned)))[as.integer(binned)]
  names(res) <- as.character(binned)
  res
}

labels <- unique(names(bincol(iris$Sepal.Length,"blue","yellow","red")))
breaks <- unique(bincol(iris$Sepal.Length,"blue","yellow","red"))
breaks <- breaks[order(labels,decreasing = TRUE)]
labels <- labels[order(labels,decreasing = TRUE)]


ggplot(iris) + 
  geom_point(aes(x=Sepal.Width, y=Sepal.Length,
                 colour=bincol(Sepal.Length,"blue","yellow","red")), size=4) +
  scale_color_identity("Sepal.Length", labels=labels, 
                       breaks=breaks, guide="legend")

enter image description here

答案 1 :(得分:7)

您可以尝试以下操作,我在下面对您的示例代码进行了适当修改:

#I am not so great at R, so I'll just make a data frame this way
#I am convinced there are better ways. Oh well.
df<-data.frame()
for(x in 1:10){
  for(y in 1:10){
    newrow<-c(x,y,sample(1:1000,1))
    df<-rbind(df,newrow)
  }
}
colnames(df)<-c('X','Y','Val')


#This is the bit you want
p<- ggplot(df, aes(x=X,y=Y,fill=cut(Val, c(0,100,200,300,400,500,Inf))))
p<- p + geom_tile() + scale_fill_brewer(type="seq",palette = "YlGn")
p<- p + guides(fill=guide_legend(title="Legend!"))

#Tight borders
p<- p + scale_x_continuous(expand=c(0,0)) + scale_y_continuous(expand=c(0,0))
p

请注意切割的战略用途是使数据离散化,然后使用颜色酿造器来制作漂亮的东西。

结果如下:

2D heatmap with discretized colour

相关问题