带有字符串标签的彩条指南 [英] Colorbar guide with string labels

查看:38
本文介绍了带有字符串标签的彩条指南的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用字符描述(例如低"和高")而不是实际数字来修改连续美学的 guide_colorbar .当对多个图使用一个图例或颜色条(热图,例如 geom_bin2d )时,这尤其有用.

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).

这里有个例子.

说给定的伪数据:

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

我可以照常做

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

并使用

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.

如何将自定义文本添加到 guide_colorbar ?或者:有没有办法将离散图例转换为颜色条并保留字符标签?

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?

推荐答案

@Atreyagaurav指出了一个非常有用的线程,但是它并不是真正的重复线程,因为OP要求提供指南.这里有一种方法,其中包括以编程方式计算休息时间.

@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'))

修改您还可以使用命名列表-您可以将其用作break参数,并且不再需要添加标签.这也可能更安全,因为标签将始终正确分配给计算值.

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))

与以上相同的情节

reprex软件包(v0.3.0)于2019年12月30日创建sup>

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

这篇关于带有字符串标签的彩条指南的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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