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
396 views
in Technique[技术] by (71.8m points)

r - Generating a color legend with shifted labels using ggplot2

I usually plot maps using GrADS, and usually I use a color legend that in the plot will look like this:

I would like to do the same using ggplot2 in R. If using simply:

g <- g + scale_fill_brewer(palette="Greens", na.value="NA", name=legendtitle)
#g is the previously saved plot with some simple options, prepared with cut()

The output is of course this:

So I'd like to be able to do two things:

  1. Shift the labels so they are between the colors, note indicating the interval above (note: renaming the labels is not the problem, shifting them is)
  2. Last label should be arrow-like, to indicate that entries above the maximum (10 in the example) are indicated in the darkest color (dark green in the example).

EDIT: Using help from the answer below, I've come to this: enter image description here

Part 1. of my question is almost solved, even if it does not look perfect. I'd really like to get rid of the white space between the colors, any idea? Part 2... I have no idea whatsoever.

My code snippet uses:
theme(legend.position="bottom", legend.key.width = unit(1, "cm"), legend.key.height = unit(0.3, "cm")) + guides(fill=guide_legend(label.position = "bottom", label.hjust = 1.2))

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here is something to get you started.

The idea is that you use cut() to create the cut points, but specify the labels in the way you desire.

By putting the legend at the bottom of the plot, ggplot automatically puts the legend labels "in between" the values.

library(ggplot2)

dat <- data.frame(x=0:100, y=runif(101, 0, 10), z=seq(0, 12, len=101))

dat$col <- cut(
  dat$z, 
  breaks=c(0, 2, 4, 6, 8, 10, Inf), 
  labels=c(2, 4, 6, 8, 10, "-->")
)

ggplot(dat, aes(x, y, col=col)) + 
  geom_point(size=10) + 
  scale_colour_brewer("", palette="Greens") +
  theme(legend.position="bottom")

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

...