2

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:

enter image description here

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"))

enter image description here

...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))

enter image description here

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?

hendra
  • 700
  • 2
  • 6
  • 16
  • [This](https://stackoverflow.com/questions/32486446/specific-variable-color-in-ggplot?rq=1) is a similar question, with an answer. [This](https://stackoverflow.com/questions/19736537/how-do-i-set-the-color-of-a-single-line-using-ggplot) shows a similar answer that might fit what you are doing more exactly. – aosmith Jun 15 '18 at 15:27

1 Answers1

0

Yo canset all colors with scale_color_manual:

ggplot(df, aes(x = x, y = y, color = z)) + geom_point()+ 
      scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))

As I know you only can set all or let all automatic. Never tried to fix some.

User 6683331
  • 692
  • 1
  • 13
  • 31