2

First I run this code and it works perfectly (all data points turn blue):

ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy), color = "blue")

But when I try move around the mapping like below, the data points turn black instead of blue.

Why is that?

ggplot(data = mpg, mapping = aes(x = displ, y = hwy), color = "blue") + geom_point() 
M--
  • 25,431
  • 8
  • 61
  • 93
  • 4
    Try `ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) + geom_point(color = "blue") ` – G5W Aug 15 '17 at 19:54
  • 4
    @G5W's comment is totally right. Just to give you a bit more insight about this; Imagine you also want to connect the points with lines (`geom_line`) and you want the line to be `red`. This is how you implement it: `ggplot(data = mpg, aes(x = displ, y = hwy)) + geom_point(color = "blue") + geom_line(color="red")`. you can use the same mapping (`aes`) for all the `geom`s. – M-- Aug 15 '17 at 19:59

1 Answers1

0

You can share the variables inside mapping between the geoms. Specifically about color, it needs to be defined outside of the aes and in the geom when setting to a constant (e.g. "blue") and not a variable (explained here: Answer to: When does the argument go inside or outside aes).

I included couple examples below to illustrate this better;

library(ggplot2)
## works fine for each geom 
ggplot(data = mpg, aes(x = displ, y = hwy)) + 
  geom_point(color = "blue") + 
  geom_line(color="red")

## doesn't work when not in the geom
ggplot(data = mpg, aes(x = displ, y = hwy), color = "blue") + 
  geom_point() 

## gets evaluated as a variable when in aes
ggplot(data = mpg, aes(x = displ, y = hwy)) + 
  geom_point(aes(color = "blue")) 

## can use a variable in aes, either in geom or ggplot function
ggplot(data = mpg, aes(x = displ, y = hwy)) + 
  geom_point(aes(color = model), show.legend = FALSE) 

M--
  • 25,431
  • 8
  • 61
  • 93