Home > Software design >  Plotting with background for each group
Plotting with background for each group

Time:06-27

I am trying to create a scatterplot having different colors on the background based on the group of instances. This is the data:

data = data.frame(Group= c(rep(1,12),rep(2,12),rep(3,12),rep(4,12),rep(5,10)), Id=1:58, Values=rnorm(58, mean=2300, sd=500))

As you can see, the Id column contains all numbers between 1 and 58, and I would like to have a different background color for each group. This is was I tried:

library(RColorBrewer)
library(colorspace)
color = c("#ffffd9","#edf8b1", "#c7e9b4", "#7fcdbb", "#41b6c4", "#225ea8")
color = adjust_transparency(color, alpha = 0.4) #adding transparacy to the colors
plot(data$Id, data$Value)
polygon(x=c(1,1,12,12), y=c(0,3500,3500,0), col=color[1], border=F)
polygon(x=c(13,13,24,24), y=c(0,3500,3500,0), col=color[2], border=F)
polygon(x=c(25,25,36,36), y=c(0,3500,3500,0), col=color[3], border=F)
polygon(x=c(37,37,48,48), y=c(0,3500,3500,0), col=color[4], border=F)
polygon(x=c(49,49,58,58), y=c(0,3500,3500,0), col=color[5], border=F)

The result is the following very ugly plot. I can't get the plots behind the polygons.

Ugly plot

Also, if anyone has a better palette to suggest, please let me know. Preferibly, I would prefer to keep using base R and not ggplot2. Thanks a lot in advance

CodePudding user response:

There are many possibilities for defining colors in base graphics. You load RColorBrewer in your code. The manual page indicates that there are 3 types of palettes depending on what you want to communicate. For example a sequential palette is a sequence of gradually changing colors:

colori <- brewer.pal(5, "Blues")
# Other options: Blues BuGn BuPu GnBu Greens Greys Oranges OrRd PuBu PuBuGn PuRd Purples RdPu Reds YlGn YlGnBu YlOrBr YlOrRd
colori = adjust_transparency(colori, alpha = 0.4)

Now we can revise your code a bit if we overprint the symbols using transparency is optional. Also we can eliminate the white bars.

plot(data$Id, data$Value, type="n")
polygon(x=c(1,1,12,12), y=c(0,3500,3500,0), col=colori[1], border=F)
polygon(x=c(12,12,24,24), y=c(0,3500,3500,0), col=colori[2], border=F)
polygon(x=c(24,24,36,36), y=c(0,3500,3500,0), col=colori[3], border=F)
polygon(x=c(36,36,48,48), y=c(0,3500,3500,0), col=colori[4], border=F)
polygon(x=c(48,48,59,59), y=c(0,3500,3500,0), col=colori[5], border=F)
points(data$Id, data$Value)

Alternate Plot

  • Related