Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a color legend with shifted labels using ggplot2

Tags:

r

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

like image 438
AF7 Avatar asked Dec 15 '25 05:12

AF7


1 Answers

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

like image 113
Andrie Avatar answered Dec 16 '25 21:12

Andrie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!