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!
CodePudding user response:
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.
CodePudding user response:
You haven't supplied a reproducible example, but as Gregor Thomas points out, this just isn't how you create named vectors in R. Here's an example using the built-in iris
dataset that shows how you could use your existing variables to get the intended results.
Firstly, I'll assign the group names and colour names to match your set-up:
Group1 <- "setosa"
Group2 <- "versicolor"
Group3 <- "virginica"
Group1col <- "red"
Group2col <- "green"
Group3col <- "blue"
To easily create a named vector, we can use setNames
:
setNames(c(Group1col, Group2col, Group3col), c(Group1, Group2, Group3))
#> setosa versicolor virginica
#> "red" "green" "blue"
So to use the named variables in your plot, you could do:
ggplot(iris, aes(Sepal.Width, Petal.Length, colour = Species))
geom_point()
scale_color_manual(values = setNames(c(Group1col, Group2col, Group3col),
c(Group1, Group2, Group3)))