0

I am trying to create a customized heat map in ggplot2, and face problem assigning customized colors to the bin values.

My current code:

df <- class19
df$NUMBER_bin <- cut(df$NUMBER, breaks = c(-Inf, 0, 5, 10, 15, 20, 25, 30, 35, 40))
colors <- c("#EDF8E9", "#BAE4B3", "#74C476", "#238B45", "pink", "yellow", "white", "black")

ggplot(data = df, aes(x = class, y = shape, fill = NUMBER_bin)) +
  geom_tile() +
  scale_fill_brewer(palette = "Reds")

I tried the solutions in ggplot2 heatmap with colors for ranged values with no success.

My data:

class19 <- structure(list(shape = c("square", "circle", "circle", "triangle", 
"triangle", "triangle", "triangle", "square", "polygon", "polygon", 
"polygon", "square", "square", "square", "square", "polygon", 
"polygon", "triangle", "triangle", "triangle", "triangle"), NUMBER = c(1, 
0, 0, 3, 2, 0, 18, 5, 0, 7, 3, 0, 3, 0, 0, 36, 4, 0, 5, 3, 0), 
    class = c("2020", "2019", "2018", "2020", "2019", "2018", 
    "2020", "2019", "2018", "2020", "2019", "2018", "2020", "2019", 
    "2018", "2020", "2019", "2018", "2020", "2019", "2018")), .Names = c("shape", 
"NUMBER", "class"), row.names = c(NA, -21L), class = c("tbl_df", 
"tbl", "data.frame"))

I've tried:

df <- class19
df$NUMBER_bin <- cut(df$NUMBER, breaks = c(-Inf, 0, 5, 10, 15, 20, 25, 30, 35, 40))
colors <- c("white", "darkblue", "blue", "lightblue", "lightgreen", "green", "darkgreen", "black")

ggplot(data = df, aes(x = class, y = shape, fill = NUMBER_bin)) +
  geom_tile()

But this is giving the colors of its own, not the ones provided.

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Nido
  • 55
  • 1
  • 1
  • 10
  • Hi OP, can you please provide `df` or another dataset that can demonstrate the question? Preference should be to share the dataset via copying and pasting the output of `dput(df)` into the body of the question. Additionally, what does the above code give you and what is your intended result? – chemdork123 Sep 09 '20 at 15:28
  • OK let me share sorry for inconvenience – Nido Sep 09 '20 at 15:30
  • 1
    ... you have to tell ggplot2 which colors to use by adding `+ scale_fill_manual(values = colors)` – stefan Sep 09 '20 at 18:02
  • THANK YOU IT WORKED – Nido Sep 09 '20 at 18:06

0 Answers0