带有字符串标签的颜色条指南,例如“低 - 中 - 高”

lez*_*eze 2 r ggplot2

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

这里有一个例子。

例子

说出给定的虚拟数据:

dd <- data.frame(xx=rnorm(100),yy=rnorm(100),zz=rep(1:10,10))
Run Code Online (Sandbox Code Playgroud)

我可以像往常一样

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

并使用隐藏颜色条注释

guides(color=guide_colorbar(ticks=F,label=F,title=element_blank()))
Run Code Online (Sandbox Code Playgroud)

我尝试的另一种方法是修改色彩美学

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

并绘制为离散的。也不是真正想要的。

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

Tje*_*ebo 6

这是如何将字符串标签添加到颜色条的一种方法,通过编程计算中断。

我正在使用一个命名的函数列表,用它创建一个用于中断的值的命名向量。如果您不命名向量,则需要指定标签。

library(ggplot2)

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

## using a named list, resulting in a named vector for the breaks
myfuns_nam <- list(min = min, med = median, max = max)

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

ggplot(dd, aes(xx, yy, color = zz)) +
  geom_point() +
  scale_color_gradient2(breaks = unlist(list_val))
Run Code Online (Sandbox Code Playgroud)


# you can also not name the function list, but then you will need to specify the labels
# 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_val2 <- 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_val2), labels = c("min", "med", "max"))
Run Code Online (Sandbox Code Playgroud)