In R, I'm trying to plot some data using ggplot's geom_point
.
Let's simulate some data:
df <- data.frame(x = rnorm(20),
y = rnorm(20),
z = LETTERS[sample(3, 20, replace = T)])
Essentially, the data are some coordinates associated with a factor label ("A", "B" or "C").
I'd like to plot them all on a scatter plot using ggplot's geom_point
, and I'd like to manually set the colour of the "C" point markers. I don't care what colour ggplot sets the markers for the "A" and "B" points.
Here's what I've come up with:
library(dplyr)
library(ggplot2)
df %>%
filter(z != "C") %>%
ggplot(aes(x, y)) +
geom_point(aes(colour = factor(z))) +
geom_point(data = filter(df, z == "C"),
aes(x, y), colour = "#C0C0C0")
...which looks like this:
That's exactly what I want, except that the marker for the "C" points doesn't appear in the legend.
Let's try again, slightly differently:
df %>%
filter(z != "C") %>%
ggplot(aes(x, y)) +
geom_point(aes(colour = factor(z))) +
geom_point(data = filter(df, z == "C"),
aes(x, y, colour = "#C0C0C0"))
...that gets the "C" marker into the legend, but it's mislabelled and the colour is not correct.
Another try:
df %>%
filter(z != "C") %>%
ggplot(aes(x, y)) +
geom_point(aes(colour = factor(z))) +
geom_point(data = filter(df, z == "C"),
aes(x, y, colour = z))
That gets the "C" marker into the legend, labelled properly, and in the correct order, but I can't set its colour.
So to reiterate: how can I manually set the colour of "C", let "A" and "B" be coloured automatically by ggplot, and show "A", "B" and "C" in the legend?