Home > Software design >  How can I add a continuous grayscale to ggplot?
How can I add a continuous grayscale to ggplot?

Time:09-22

I am trying to add a grayscale color ramp to a continuous color scale in a ggplot for the variable z. A sample is below but I haven't been able to figure out how to make a continuous gray scale.

library(ggplot2)

x <- seq(0,10,1)
y <- seq(11,20,1)
z <- seq(21,30,1)

df <- data.frame(cbind(x,y,z))

ggplot(df,aes(x,y)) 
  geom_point(aes(color = z), size = 3) 
  scale_color_continuous(type = "viridis")

CodePudding user response:

One way of easily changing the color to a scale of grays is using scale_color_distiller. Just substitute scale_color_continuous in your script for the following line.

scale_color_distiller(type = "seq",
                        direction = -1,
                        palette = "Greys")

plot

CodePudding user response:

# First you set the border of the grey colors
grey_range <- colorRampPalette(c("#737373", "#F0F0F0"))

x <- seq(0,10,1)
y <- seq(11,20,1)
z <- seq(21,30,1)

# Then you set the range of grey colors
color_z <- grey_range(length(z))  

df <- data.frame(cbind(x,y,z))

# Lastly you assign the colors to the factor Z
ggplot(df,aes(x,y, color=as.factor(z))) 
  geom_point(size = 3)  
  scale_color_manual(values=setNames(color_z, levels(df$z)))  
  theme_bw()

enter image description here


The very easy way is to do this

ggplot(df,aes(x,y, color=as.factor(z))) 
  geom_point(size = 3)  
  scale_colour_grey()

# With the start = 0.2, end = 0.8 option you can regulate the intensity and direction of the grey

enter image description here

  • Related