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

14 plot r heatmap ggplot2

假设我有这个情节:

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

什么是离散色标的正确方法,如下面接受的答案下面显示的图(ggplot stat_bin2d图中的渐变断点)?

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

除了我正在绘制散点图而不是像geom_tile/ heatmap 这样的东西.

谢谢.

Rol*_*and 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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Ric*_*ard 8

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

#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
Run Code Online (Sandbox Code Playgroud)

注意切割的战略用途是使数据离散化,然后使用颜色酿造器使事情变得美观.

结果如下.

具有离散色的2D热图