Reputation: 16393
I am producing a number of scatter plots, with the u-v values having a third dimension w, that can only take 3 values (0,1,2). I want a constant colour palette for each of my graphs so the 3 values always have the same colour in each graph. However, I am getting varying colours assigned to the values. An example is this:
library(ggplot2)
library(gridExtra)
u <- c(1.0968145, 0.2566922, 2.6884111, 2.3855156, 0.8794000, 2.4317190)
v <- c(-0.3252739, 0.9596294, -1.4270491, 0.7009061, 0.3631149, 1.8298008)
w <- c(1, 0, 1, 1, 1, 2)
df1 <- data.frame(u, v, w)
p1 <- ggplot(df1, aes(x=u, y=v, color=w )) + geom_point(show.legend = FALSE)
u <- c(0.9827588, 2.2715139, 1.0160009, -1.0461050, 0.0208908, 2.5948499)
v <- c(1.6068334, 0.7113232, 2.6927960, 3.4466515, 0.7541632, -0.2872779)
w <- c(0, 1, 0, 0, 0, 1))
df2 <- data.frame(u, v, w)
p2 <- ggplot(df2, aes(x=u, y=v, color=w )) + geom_point(show.legend = FALSE)
grid.arrange(p1, p2)
This code produces a plot like this:
Now the first frame has all three values and the these are seen in the top plot. The top right-most point in that plot (2.43, 1.83) has a value of 2 which is shown as light blue. The second frame only has values 0 and 1, but the lower plot shows this frame, and it can be seen that the two lower-left points, which have a value of 1, also code to light blue.
How do I fix this?
Upvotes: 1
Views: 129
Reputation: 48251
One solution consists of the following:
w
is a factorw
has the same factor levels in all data framesdrop = FALSE
in scale_colour_discrete
or scale_colour_manual
.For instance,
w <- c(1, 0, 1, 1, 1, 2)
df1 <- data.frame(u, v, w)
df1$w <- factor(df1$w) # New
p1 <- ggplot(df1, aes(x = u, y = v, color = w )) + geom_point(show.legend = FALSE) +
scale_colour_discrete(drop = FALSE) # New
u <- c(0.9827588, 2.2715139, 1.0160009, -1.0461050, 0.0208908, 2.5948499)
v <- c(1.6068334, 0.7113232, 2.6927960, 3.4466515, 0.7541632, -0.2872779)
w <- c(0, 2, 0, 0, 0, 2) # Switched from 1 to 2
df2 <- data.frame(u, v, w)
df2$w <- factor(df2$w, levels = c("0", "1", "2")) # New
p2 <- ggplot(df2, aes(x = u, y = v, color = w )) + geom_point(show.legend = FALSE) +
scale_colour_discrete(drop = FALSE) # New
grid.arrange(p1, p2)
So, now in the lower plot points corresponding to 2 are blue just like that single point in the upper plot, even though w
only takes values 0 and 2 in the lower one.
Upvotes: 1