ay__ya
ay__ya

Reputation: 463

ggplot2 function scale_fill_stepsn colors do not match

I have some codes that want to show a map with unequal color breaks and assign each category with a specific color. I used the scale_fill_stepsn function.

Here are my codes:

ggplot(data = rate) + 
    geom_sf(aes(fill = rate))+theme_bw()+
      scale_fill_stepsn(name = "Test Rate \n (n/1000)", 
                    colors =c("#999999","#6666FF", "#FFFF66","#FF6633"),
                    breaks = c(0,1, 10, 100),
                    labels=scales::label_number(accuracy=1),
                    show.limits = TRUE) +
    annotation_north_arrow(location = "tl", which_north = "true", 
        pad_x = unit(0.1, "in"), pad_y = unit(0.05, "in"),
        height = unit(1, "cm"),
        width = unit(1, "cm"),
        style = north_arrow_fancy_orienteering)+
    annotation_scale(location = "bl", width_hint = 0.2)

The Figure

The exact colours I put in the function shows below, which do not match the colour in the result figure.

scales::show_col(c("#999999","#6666FF", "#FFFF66","#FF6633"))

enter image description here

data

Upvotes: 1

Views: 535

Answers (1)

Jon Spring
Jon Spring

Reputation: 66425

If I add trans = scales::log10_trans(), to the scale_fill_stepsn I get better results for this reproducible example, because my breaks are log distributed, so my gradient should be too. Otherwise the gradient will apply linearly along 0:107, and most values will be in muddled gray land.

ggplot(data.frame(val = c(0, 1, 10, 100, 107), x = 1:5),
       aes(x, 0, fill = val)) +
  geom_tile() +
  scale_fill_stepsn(name = "Test Rate \n (n/1000)", 
                    colors =c("#999999","#6666FF", "#FFFF66","#FF6633"),
                    breaks = c(0,1, 10, 100), 
                    trans = scales::pseudo_log_trans(), #  ADDED THIS LINE
                    labels=scales::label_number(accuracy=1),
                    show.limits = TRUE) 

With

enter image description here

Without

enter image description here

Upvotes: 1

Related Questions