Colorbar guide with string labels

余生颓废 提交于 2021-02-19 05:52:15

问题


I would like to modify the guide_colorbar of a continuous aesthetic with character descriptions, e.g., 'low' and 'high', instead of actual numbers. This can be especially useful when using one legend or colorbar for multiple plots (heatmaps, e.g, geom_bin2d).

Here an example.

Say given dummy data:

dd <- data.frame(xx=rnorm(100),yy=rnorm(100),zz=rep(1:10,10))

I can do the usual

ggplot(dd,aes(xx,yy,color=zz))+
  geom_point()+
  viridis::scale_color_viridis(option='A',direction=-1)

and hide colorbar annotations using

guides(color=guide_colorbar(ticks=F,label=F,title=element_blank()))

Another approach I tried is modifying the color aesthetics with

factor(zz,labels=c('low',2:9,'high'))
...
guides(color=guide_legend(override.aes=list(size=5,shape=15)))

and plotting as discrete. Also not really desired.

How do I add customized text to guide_colorbar? Or: Is there a way to convert a discrete legend to a colorbar and keeping the character labels?


回答1:


@Atreyagaurav has pointed to a very useful thread, but it's not a real duplicate because the OP was asking for the guide. Here one way which includes programmatical calculation of the breaks .


    library(ggplot2)

    dd <- data.frame(xx=rnorm(100),yy=rnorm(100),zz=rep(1:10,10))

    # list of functions to calculate the values where you want your breaks
    myfuns <- list(min, median, max)
    # use this list to make a list of your breaks
    list_val <- lapply(myfuns, function(f) f(dd$zz))

    # to use the list, unlist it first
    ggplot(dd,aes(xx,yy,color=zz))+
      geom_point()+
      scale_color_gradient2(breaks = unlist(list_val), labels = c('min','med','max'))

edit You can also use a named list - you can use this as your break argument and don't need to add labels anymore. This may also be safer because the labels will always be correctly assigned to the calculated values.

    myfuns_nam <- list(min = min, med = median, max = max)

    list_val_nam <- lapply(myfuns_nam, function(f) f(dd$zz))

    ggplot(dd,aes(xx,yy,color=zz))+
      geom_point()+
      scale_color_gradient2(breaks = unlist(list_val_nam))

Same plot as above

Created on 2019-12-30 by the reprex package (v0.3.0)



来源:https://stackoverflow.com/questions/59531865/colorbar-guide-with-string-labels

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!