Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding border or background to scale legend guide_colorbar in ggplot2

Tags:

r

ggplot2

I have a colorbar within ggplot graph ranging from white to red and the white border is not very good visible on the white background.

Is there a way to color the tick marks in the legend differently or adding a border around the gradient scale?

Here is a minimal example:

df <- data.frame(x <- rnorm(10),
                 y <- rnorm(10),
                 fill <- rnorm(10))

ggplot(df, aes(x, y, fill = fill)) + 
  geom_point() + 
  scale_fill_gradient(low = 'white', high = 'red')

enter image description here

like image 670
drmariod Avatar asked Apr 22 '15 09:04

drmariod


People also ask

How do I change the background color in legend?

On the Display tab, expand Background. For Symbol, click the down arrow to open the color palette. Choose a color to change the legend background.

How do I add a legend in ggplot2?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

How do I change the legend text in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))


2 Answers

In the latest ggplot2 (development version, to be released as 2.3), this now works:

# devtools::install_github("tidyverse/ggplot2") # do this once
library(ggplot2)
df <- data.frame(x <- rnorm(10),
                 y <- rnorm(10),
                 fill <- rnorm(10))

ggplot(df, aes(x, y, fill = fill)) + 
  geom_point() + 
  scale_fill_gradient(low = 'white', high = 'red',
    guide = guide_colorbar(frame.colour = "black", ticks.colour = "black"))

enter image description here

like image 88
Claus Wilke Avatar answered Oct 19 '22 08:10

Claus Wilke


Found a solution for my problem by using element_rect and fill argument.

df <- data.frame(x <- rnorm(10),
                 y <- rnorm(10),
                 fill <- rnorm(10))

ggplot(df, aes(x, y, fill = fill)) + 
  geom_point() + 
  scale_fill_gradient(low = 'white', high = 'red') + 
  theme(legend.background = element_rect(fill = "grey95"))

enter image description here

I would prefer a border just around the colorbar, but this seems not possible...

like image 43
drmariod Avatar answered Oct 19 '22 07:10

drmariod