Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

r - Label minimum and maximum of scale fill gradient legend with text: ggplot2

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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...