user11916948
user11916948

Reputation: 954

Color according to group but intensity according to injection, how to accomplish?

I have made a color for each group in this data frame. I wonder how I can set a intensity related to injection order. The color should be as respective group but intensity of the color should vary with injection , going from low intensity to high. Does anyone have a suggestion on how to do this?

Many thanks!

library(RColorBrewer)
id <- rep(1:4, each=5)
group <- rep(LETTERS[1:4], each=5)
inj<- rep(1:5,4)
q1 <- sample(1:50,20)
q2 <- sample(1:50,20)
df <- data.frame(id, group, inj, q1,q2)
df

group_col <- rep(paste0(brewer.pal(5,"Paired")[1:5], "60"), each=4)
df$group_col <-group_col
head(df)

   id group inj q1 q2 group_col
1  1     A   1 31  7 #A6CEE360
2  1     A   2 44  1 #A6CEE360
3  1     A   3 34 21 #A6CEE360
4  1     A   4 49 16 #A6CEE360
5  1     A   5  1 20 #1F78B460
6  2     B   1 42 13 #1F78B460

Upvotes: 2

Views: 314

Answers (1)

xilliam
xilliam

Reputation: 2259

First consider that (at least for ggplot2) the alpha (opaqueness) parameter is encoded with 8-digit hex color codes, with the last two letters of the eight comprising the alpha channel suffix. This set of strings represents the suffixes that range from 45% thru 100% opaqueness.

alpha_suffix <- c("73", "99","B3","D3","FF")

In your original code, there was a line that I believe needed adjustment. (Because your colors were not lined up with the 'groups'). One 6-digit hex color per group can be had this way:

library(RColorBrewer)

set.seed(1)
id <- rep(1:4, each=5)
group <- rep(LETTERS[1:4], each=5)
inj<- rep(1:5,4)
q1 <- sample(1:50,20)
q2 <- sample(1:50,20)
df <- data.frame(id, group, inj, q1,q2)

group_col <- rep(brewer.pal(4,"Paired"), each=5) # ADJUSTED LINE

Then one can append the alpha suffixes with the 6-digit hex codes, and assign them to the df object as follows. This lines up each color in 'group_col' with the five levels of 'inj'.

df$group_col <- paste0(group_col, rep(alpha_suffix, 4))

By doing it this way, one can use 'group_col' for the color aesthetic, as well as for the values argument in scale_color_manual. Here's what a ggplot2 scatterplot looks like with these colors.

library(ggplot2)

ggplot(df, aes(x= q1, y= q2, color = group_col))+
  geom_point(stat="identity", size = 8) +
  scale_color_manual(values = df$group_col)+
  theme_minimal()

scatter4 The opacity effects would be easier to see if you try another RColorBrewer palette, like this, instead of the "Paired":

group_col <- rep(brewer.pal(4,"Set1"), each=5)

And finally, in base R 'group_col' could be implemented like this:

plot(df$q1,df$q2,col= df$group_col,pch=16,cex=4)

Upvotes: 3

Related Questions