5
votes

I'm tinkering with geom_point trying to plot the following code. I have converted cars$vs to a factor with discrete levels so that I can visualize both levels of that variable in different colors by assigning it to "fill" in the ggplot aes settings.

cars <- mtcars
cars$vs <- as.factor(cars$vs)

ggplot(cars,aes(x = mpg, y = disp, fill = vs)) +
  geom_point(size = 4) +
  scale_fill_discrete(name = "Test")

The result is this:

As you can see, the graph does not differentiate between both "fill" conditions via color. However, it preserves the legend label I have specified in scale_fill_discrete.

Alternatively, I can plot the following (same code, but instead of "fill", use "color")

cars <- mtcars
cars$vs <- as.factor(cars$vs)

ggplot(cars,aes(x = mpg, y = disp, color = vs)) +
  geom_point(size = 4) +
  scale_fill_discrete(name = "Test")

enter image description here

As you can see, using "color" instead of "fill" differentiates between the levels of the factor via color, but seems to override any changes I make to the legend title using scale_fill_discrete.

Am I using "fill" incorrectly? How can I plot different levels of a factor in different colors using this method and have control over the plot legend vis scale_fill_discrete?

2

2 Answers

6
votes

Since you are using color as mapping, you can use scale_color_* to change the corresponding attributes instead of scale_fill_*:

ggplot(cars,aes(x = mpg, y = disp, color = vs)) +
      geom_point(size = 4) +
      scale_color_discrete(name = "Test") 

enter image description here

4
votes

To use a fill with geom_point you should use a fill-able shape:

ggplot(cars,aes(x = mpg, y = disp, fill = vs)) +
  geom_point(size = 4, shape = 21) +
  scale_fill_discrete(name = "Test")

See ?pch, which shows that shapes 21 to 25 can be colored and filled with different colors.ggplot will not use the fill unless the shape is one that is fill-able. This behavior has changed a bit in different versions, as seen in the NEWS file.

There's no reason to use fill with geom_point unless you want the outline and fill colors of the points to be different, so the other answer recommending color is probably what you want.