Modify gradient colors in graphs in ggplot2

Asked

Viewed 1,974 times

9

How do I modify the gradient colors of a graph in ggplot?

Like, I’m not getting to put a continuous color scale between white and red, I’ve tried a variety of things but still haven’t answered me.

library('ggplot2')  
Tipo = c("Casa", "Rua", "Bairro", "Municipio")  
Freq = c(100, 150, 175, 300)  
dados = data.frame(Tipo,Freq)  

ggplot(data=dados, aes(x=Freq, y=Tipo, fill=Freq)) +  
       geom_label(label=rownames(dados), color="white", size=3) +  
       labs(x = "Frequência", y = "Tipo")

2 answers

11


Use the function scale_fill_gradient for this:

ggplot(data=dados, aes(x=Freq, y=Tipo, fill=Freq)) +  
  geom_label(label=rownames(dados), color="black", size=3) +  
  labs(x = "Frequência", y = "Tipo") +
  scale_fill_gradient(low="#FFFFFF", high="#FF0000")

inserir a descrição da imagem aqui

The easiest way to use it is to define which color is the lower limit of your scale (low) and what is the upper limit (high). Colors are displayed in the RGB standard (Red, GReen, BLue) hexadecimal. Briefly, this pattern defines each color with a shape code #RRGGBB, in which

  • RR is a hexadecimal number between 00 and FF, thus allowing 256 levels of red

  • GG is a hexadecimal number between 00 and FF, thus allowing 256 levels of green

  • BB is a hexadecimal number between 00 and FF, thus allowing 256 levels of blue

So when I put low="FFFFFF", I’m saying I want the most red, green and blue in my color. The result of this is white, because this color is the mixture of all other colors.

On the other hand, when I put high="FF0000", I am saying I want the maximum of red and the minimum of green and blue in my color. The result of this is pure red.

10

My solution is very similar to @Marcus Nunes, but with a difference that seems important to me, so I also decided to answer.
The difference is in the color vector used in geom_label. To have contrast with the background the colors are or "red" or "white" depending on the values of Freq are smaller or greater than the median of that vector dados.

There is still another difference but of lesser importance. The function scale_fill_gradient accepts limits as strings with color names, thus avoiding having to know the corresponding RGB values. (It doesn’t hurt to know, by the way, it’s actually very useful.)

cols <- ifelse(dados$Freq < median(dados$Freq), "red", "white")

ggplot(data=dados, aes(x=Freq, y=Tipo, fill=Freq)) +  
  geom_label(label=rownames(dados), size=3, colour=cols) +  
  labs(x = "Frequência", y = "Tipo") +
  scale_fill_gradient(low = "white", high = "red")

inserir a descrição da imagem aqui

  • Excellent addition to the contrast in the figures.

  • Ball show, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.