首页 文章

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

提问于
浏览
10

假设我有这个情节:

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 回答

  • 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

  • 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

相关问题