Make legend for scale_fill_continuous continuous scale instead of discrete

Advertisements

I’m using the function of scale_fill_gradientn() which normally should produce a continuous scale as the legend but somehow if I use the following code attached below the outcome produces a legend with boxes of colours as discrete values

  ggplot(aes(x=grouping,y=person,fill=score)) + 
  geom_tile(stat = "identity",position = "identity",colour="black",size=1) + 
  facet_grid(family~functional,switch = "y") +
  scale_fill_gradientn(colours = c("white","orange","red"),
    limits=c(0,100),breaks = c(0,50,100),labels=c("min","mid","max"),
    guide = guide_legend(direction = "horizontal",title.position = "bottom")) +
    labs(fill = "Average Percentage")

I notice that as long as I remove the guide argument from the scale_fill_gradientn() function it would give me back a continuous scale i.e.

scale_fill_gradientn(colours = c("white","orange","red"),
    limits=c(0,100),breaks = c(0,50,100),labels=c("min","mid","max"))

But then my question would be why does this occur and if I have to refrain from using the guide argument how can I add a black border around the scale (like the picture above with the discrete colour boxes) as well as adjust the positioning of the title and labels e.g. put the legend title below the colour bar and labels above the colour bar? Thanks a lot!

>Solution :

Here is a potential solution using the palmer penguins dataset as a minimal, reproducible example:

library(tidyverse)
library(palmerpenguins)

penguins %>% 
  na.omit() %>%
  ggplot(aes(x = body_mass_g, y = bill_length_mm, fill = flipper_length_mm)) +
  geom_point(shape = 21, size = 3) +
  scale_fill_gradientn(colours = c("white", "orange", "red"),
                       limits = c(170, 240), breaks = c(180, 205, 235),
                       labels = c("min", "mid", "max"),
                       guide = guide_legend(direction = "horizontal",
                                            title.position = "bottom"))


penguins %>% 
  na.omit() %>%
  ggplot(aes(x = body_mass_g, y = bill_length_mm, fill = flipper_length_mm)) +
  geom_point(shape = 21, size = 3) +
  scale_fill_gradientn(colours = c("white", "orange", "red"),
                       limits = c(170, 240), breaks = c(180, 205, 235),
                       labels = c("min", "mid", "max"),
                       guide = guide_colourbar(direction = "horizontal",
                                               title.position = "bottom"))

Created on 2022-07-25 by the reprex package (v2.0.1)

Does this solve your problem?

Leave a ReplyCancel reply