使用文本标记最小和最大刻度填充渐变图例:ggplot2

问题描述 投票:16回答:1

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

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

这种类型的缩放/填充是否可以在ggplot2中使用此文本标签?

# 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")
r ggplot2 label legend fill
1个回答
34
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.