简体   繁体   中英

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:

在此处输入图片说明

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?

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

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