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

时间:2023-02-09 21:47:24

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:

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

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

scale_labels.continuous(scale,breaks)中的错误:中断和标签的长度不同

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

这种类型的缩放/填充是否可以在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")

1 个解决方案

#1


27  

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.

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

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

#1


27  

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.

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

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