I am finalizing the representation of my dataset using ggplot2 and for the sake of clarity I would need a coloring scheme that defies standard ggplot2 "logic". Below is a fake dataset to show you my needs in essence:
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
dose=rep(c("D0.5", "D1", "D2"),2),
len=c(6.8, 15, 33, 4.2, 10, 29.5))
head(df2)
supp dose len
1 VC D0.5 6.8
2 VC D1 15.0
3 VC D2 33.0
4 OJ D0.5 4.2
5 OJ D1 10.0
6 OJ D2 29.5
Here is the basic representation I'm using giving the plot below:
ggplot(data=df2, aes(x=dose, y=len, fill=supp))
geom_bar(stat="identity", position=position_dodge())
What I would need is to apply a presonalized color palette (myPalette <- c("#05eb92", "#119da4", "#ffc857")
) only to the VC
series, while coloring OC
series Black. Below is the expected plot I need. I am aware that this coloring scheme defies ggplot2 "logic" but I was wondering whether there is an easy way to apply it to my needs. Thanks.
CodePudding user response:
I would create a dummy
variable in your input df2
for the ggplot
fill
aesthetic. Here, "-999" refers to "OJ" and will be coloured in black.
I've also updated your myPalette
to include black in it, and also setNames
to it so that only "-999" will have a corresponding "black" value.
library(tidyverse)
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
dose=rep(c("D0.5", "D1", "D2"),2),
len=c(6.8, 15, 33, 4.2, 10, 29.5))
myPalette <- c("#05eb92", "#119da4", "#ffc857")
myPalette_with_black <- setNames(c(myPalette, "black"),
c(as.character(seq_along(myPalette)), "-999"))
df2 <- df2 %>%
group_by(supp) %>%
mutate(dummy = ifelse(supp == "VC", as.character(row_number()), "-999"))
ggplot(data=df2, aes(x=dose, y=len, fill = dummy))
geom_bar(stat="identity", position=position_dodge())
scale_fill_manual(values = myPalette_with_black)
theme(legend.position = "none")
Created on 2022-03-12 by the reprex package (v2.0.1)