JoeF JoeF - 1 month ago 6
R Question

Can't set colour manually with ..count .., geom_point and facet_wrap

I've seen a lot of variations on this problem, as well as the error message I get. However, none of the situations is like what I'm trying to do. Say I have some data that looks a bit like this:

r <- c("zero", "r", "zero", "zero", "r", "r", "r", "zero", "r", "r")

store <- c("Saks", "Saks", "Klein's", "Macy's", "Saks", "Klein's", "Macy's", "Macy's", "Klein's", "Saks")

dat <- data.frame(r, store)

# Specify the colors
cols <- c(r = "#1B79A5", zero = "#FD7701")


I can get what I want with the default ggplot2 colours as follows:

ggplot(data = dat, aes(x = r, shape = r, colour = r, ..count..)) +
geom_point(stat = "count", size = 3) +
facet_wrap(~ store)


The problem occurs when I try to add custom colours. If I don't add a
facet_wrap()
layer, there isn't a problem:

ggplot(data = dat, aes(x = r, fill = r, shape = r, ..count..)) +
geom_point(stat = "count", color = cols, size = 3)


However, if I add a facet_wrap() layer

ggplot(data = dat, aes(x = r, fill = r, shape = r, ..count..)) +
geom_point(stat = "count", color = cols, size = 3) +
facet_wrap(~store)


I get an error message,
Aesthetics must be either length 1 or the same as the data (6): colour, size
.

Again, there are lots of posts here with a similar error message, but none were doing the same thing I am trying.

I also tried a lot of variation with trying
scale_fill_manual(values = cols)
but that didn't do anything: no error message, but just black points.

(I typically use bar plots in this scenario without difficulties, but I'm trying to figure out different aspects of ggplot2, so I thought I would try this instead).

Answer

You should just need to add scale_color_manual() to your first plot, which was working for you but with the default colors.

ggplot(data = dat, aes(x = r,  shape = r, colour = r, ..count..)) +
geom_point(stat = "count", size = 3) +
facet_wrap(~ store) +
    scale_color_manual(values = c("#1B79A5", "#FD7701"))

enter image description here