简体   繁体   中英

Adding a unit label to a color gradient legend in ggplot2

Lets say I have plotted some variables in a figure, and linked the color of the points on the plot to some other variable. This is easy to do in ggplot2 and generates the following figure:

require(ggplot2)
miss <- sample(c(NA, 1:5), nrow(mtcars), rep = TRUE)
qplot(mpg, wt, data = mtcars, colour = miss) +
  scale_colour_gradient(na.value = "black")

在此处输入图片说明

However, I want the 'miss' legend to have units. Specifically I want those units to be watts meter^-2 hour^-1 (with appropriately formatted superscripts). What is the most straight forward way to add this?

Create a vector containing the label text you desire, including any special plotmath expressions, then use parse to evaluate it into an expression that will be rendered properly in the plot. Then, in the plot code, set the desired breaks using the breaks argument, with the corresponding labels in the labels argument.

labs = parse(text=paste0(1:5, "~watts%.%meter^-2"))

qplot(mpg, wt, data = mtcars, colour = miss) +
  scale_colour_gradient(na.value = "black", breaks=1:5, labels=labs)

在此处输入图片说明

UPDATE: You can put the units beside the legend, but you'll probably need to tweak it manually to get the placement right (though someone who understands the grob structure of a ggplot better than I do might be able to automate it). Also, even though I've turned off clipping, the legend grob will still cover the units annotation if it gets too close to the legend. I'm not sure how to fix that.

p1 = qplot(mpg, wt, data = mtcars, colour = miss) +
  scale_colour_gradient(na.value = "black") + 
  annotate(x=max(mtcars$mpg) + 0.25*diff(range(mtcars$mpg)), 
           y=mean(range(mtcars$wt)) - 0.1,
           label=lbl, geom="text", parse=TRUE, angle=-90, size=3.3) +
  coord_cartesian(xlim=range(mtcars$mpg)) +
  theme(plot.margin=unit(c(0.5,2,0.5,0.5), "lines"))

# Turn off clipping
gt <- ggplot_gtable(ggplot_build(p1))
gt$layout$clip <- "off"
grid.draw(gt)

在此处输入图片说明

In case you wanted it only above in the legend this would be the solution

require(ggplot2)
miss <- sample(c(NA, 1:5), nrow(mtcars), rep = TRUE)
qplot(mpg, wt, data = mtcars, colour = miss) +
scale_colour_gradient(na.value = "black", name = bquote('' ~W ~ m^-2~h^-1*''))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM