PatrickT
PatrickT

Reputation: 10530

change colors to black in existing ggplots

This is a question about the ggplot2 package (author: Hadley Wickham). I have existing ggplot objects with distinct colors (resp shapes, linetype, fill...) that I would like to map to a single color, e.g. black. What is the recommended approach?

Clarification: I have to work with these ggplot objects: I cannot re-make them

A ggplot with variables grouped as factors: this is the plot object p I need to work with

p <- ggplot(mtcars, aes(x = mpg, y = wt, group = factor(cyl), colour = factor(cyl))) + 
    geom_point(size = 5)

enter image description here

Several approaches I know of:

1. scale_colour_grey hack

p + scale_colour_grey(start = 0, end = 0) + # gives correct, useless legend
    guides(color = FALSE)

The shorter p + scale_colour_grey(0,0) does not work, you have to be explicit about start and end.

2. scale_colour_manual with rep() hack

p + scale_colour_manual(values = rep("black",3)) # gives correct, useless legend

The simpler scale_colour_manual(values = "black") does not work. This was probably the most intuitive approach. Having to specify the length of the vector makes it less attractive an approach.

3. geom_point() recalled

p + geom_point(colour = "black") + # gives incorrect legend
    guides(color = FALSE)

enter image description here

It is well documented that the following is not allowed:

 p + scale_colour_manual(colour = "black")
Error in discrete_scale(aesthetic, "manual", pal, ...) : 
  unused argument (colour = "black")

Upvotes: 3

Views: 2653

Answers (2)

eipi10
eipi10

Reputation: 93871

If you just want to set the points to black and get rid of the color legend, I think you can just to this:

p + scale_colour_manual(values=rep("black",length(unique(mtcars$cyl))),
                        guide=FALSE)

Upvotes: 4

Gregor Thomas
Gregor Thomas

Reputation: 146050

Removing the color mapping directly seems to work:

p_bw = p
p_bw$mapping$colour = NULL
gridExtra::grid.arrange(p, p_bw)

enter image description here

Upvotes: 5

Related Questions