Michael Szczepaniak Michael Szczepaniak - 2 months ago 38
R Question

ggplot2 legend title position

I use the following code to create a heatmap:

library(ggplot2)
gamma_df <- read.csv("https://www.dropbox.com/s/1kpclcq7o907t61/blogs_test.csv?dl=1")
p <- ggplot(data = gamma_df, aes(x=gamma2, y=gamma3, fill=predacc)) + geom_tile()
p <- p + scale_fill_gradient2(low = "white", high = "red",
limit = c(0.1,0.4), space = "Lab",
name="Discounts")
p <- p + theme(legend.position="right")
p


and my results look like this:

enter image description here

I've been unsuccessful in moving the legend title up a little bit so that it doesn't overlap the values. I tried adding

p + guides(color=guide_colourbar(title.vjust=3))


as suggested here with various values for the title.vjust parameter, but without any luck. Anyone know the magic for this?

Answer

A quick solution is just to add a newline at the end of the legend title:

library(ggplot2)
gamma_df <- read.csv("https://www.dropbox.com/s/1kpclcq7o907t61/blogs_test.csv?dl=1")
p <- ggplot(data = gamma_df, aes(x=gamma2, y=gamma3, fill=predacc)) + geom_tile()
p <- p + scale_fill_gradient2(low = "white", high = "red",
                              limit = c(0.1,0.4), space = "Lab",
                              name="Discounts\n")
p <- p + theme(legend.position="right")
p

though you might be better off just getting rid of the limit =

gamma_df <- read.csv("https://www.dropbox.com/s/1kpclcq7o907t61/blogs_test.csv?dl=1")
    p <- ggplot(data = gamma_df, aes(x=gamma2, y=gamma3, fill=predacc)) + geom_tile()
    p <- p + scale_fill_gradient2(low = "white", high = "red",
                                  space = "Lab",
                                  name="Discounts")
    p <- p + theme(legend.position="right")
    p