'Why cant i use vector in scale fill manual?
I Want to create a graph that uses scale fill manual to fill colours of graph.
G3 <- ggplot(preTMM, aes(Var2, value, fill=group))+
geom_boxplot()+
Gtheme2+
xlab("")+
ylab("Log-CPM")+
scale_fill_manual(values=c("pCDNA"="grey59","M"= "steelblue3"),
breaks=c("pCDNA","M"))+
guides(fill=FALSE)
This works fine, but if i want to add it via a vector that was made previously;
DGEGroup1 <- "pCDNA"
DGEGroup2 <- "M"
DGEGroup1Col <- "grey59"
DGEGroup2Col <- "steelblue3"
it doesnt work.. what am I doing wrong.
G3 <- ggplot(preTMM, aes(Var2, value, fill=group))+
geom_boxplot()+
Gtheme2+
xlab("")+
ylab("Log-CPM")+
scale_fill_manual(values=c(DGEGroup1=DGEGroup1Col,DGEGroup2=DGEGroup1Col),
breaks=c(DGEGroup1,DGEGroup2))+
guides(fill=FALSE)
I want to do this so all the graphs can be controlled by one colour vector if that makes sense?
Thanks in advance for help!
Solution 1:[1]
That syntax for a named vector doesn't work because R functions (including c()) don't require quotes for argument names:
x = "a"
y = "b"
c(x = y)
# x
# "b"
## See how the name is literally `"x"`, not `"a"`
This is a Good Thing. It means that functions that have an argument named x don't break when you also have an object named x.
For your purpose, a good fix is to use setNames to name the vector. (You could also use names(vector) <- ... but setNames lets you keep it as a one-liner with an anonymous vector, much like you already have it).
values = setNames(
c(DGEGroup1Col, DGEGroup2Col),
nm = c(DGEGroup1, DGEGroup2)
)
However, if you're doing this for multiple plots I'd strongly suggest pulling out the definition of that vector earlier in you code so you're not repeating this syntax.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
