使用文本标记缩放填充渐变图例的最小值和最大值:ggplot2 [英] Label minimum and maximum of scale fill gradient legend with text: ggplot2

查看:732
本文介绍了使用文本标记缩放填充渐变图例的最小值和最大值:ggplot2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ggplot2 中创建了一个使用 scale_fill_gradientn 的图。我想在缩放图例的最小和最大值处添加文本。例如,在图例最小显示最小和图例最大显示最大时。有使用离散填充和添加数字而不是文本标签的帖子(例如此处),但我不确定如何在 scale_fill_gradientn 中使用标签功能仅在最小值和最大值处插入文本。目前我容易出错:

scale_labels.continuous(scale,breaks)中的错误:
Breaks and labels are不同的长度



对于这种类型的比例/填充,ggplot2中是否可以使用此文本标签?

 #这里的示例代码仅用于说明目的。 
#从ggplot2文档创建数据框
df< - expand.grid(x = 0:5,y = 0:5)
df $ z < - runif(nrow( df))

#plot
ggplot(df,aes(x,y,fill = z))+ geom_raster()+
scale_fill_gradientn(colors = topo.colors(7 ),na.value =transparent)


解决方案

scale_fill_gradientn()您应该提供两个参数: breaks = labels = 具有相同的长度。使用参数 limits = ,可以将colorbar扩展到所需的最小值和最大值。

  ggplot(df,aes(x,y,fill = z))+ geom_raster()+ 
scale_fill_gradientn(colors = topo.colors(7),na.value =transparent,
breaks = c(0,0.5,1),labels = c(Minimum,0.5,Maximum),
limits = c(0,1))


I have a plot created in ggplot2 that uses scale_fill_gradientn. I'd like to add text at the minimum and maximum of the scale legend. For example, at the legend minimum display "Minimum" and at the legend maximum display "Maximum". There are posts using discrete fills and adding labels with numbers instead of text (e.g. here), but I am unsure how to use the labels feature with scale_fill_gradientn to only insert text at the min and max. At the present I am apt to getting errors:

Error in scale_labels.continuous(scale, breaks) : Breaks and labels are different lengths

Is this text label possible within ggplot2 for this type of scale / fill?

# The example code here produces an plot for illustrative purposes only.
# create data frame, from ggplot2 documentation
df <- expand.grid(x = 0:5, y = 0:5) 
df$z <- runif(nrow(df))

#plot
ggplot(df, aes(x, y, fill = z)) + geom_raster() + 
scale_fill_gradientn(colours=topo.colors(7),na.value = "transparent")

解决方案

For scale_fill_gradientn() you should provide both arguments: breaks= and labels= with the same length. With argument limits= you extend colorbar to minimum and maximum value you need.

ggplot(df, aes(x, y, fill = z)) + geom_raster() + 
      scale_fill_gradientn(colours=topo.colors(7),na.value = "transparent",
                           breaks=c(0,0.5,1),labels=c("Minimum",0.5,"Maximum"),
                           limits=c(0,1))

这篇关于使用文本标记缩放填充渐变图例的最小值和最大值:ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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