I wonder how it's working to set aesthetics in ggplot
. How it's possible to know where to put the aes
in ggplot
?
Consider this code:
p<- ggplot(mtcars, aes(wt, mpg, colour = "red"))
# A basic scatter plot
hello =p + geom_point(size = 4)
hello
goodbye=p + geom_point(aes(colour = factor(cyl)), size = 4)
goodbye
Here, it's possible to see that the colour red is applied to the points in the first graph (hello), and in the second (goodbye) it's getting the colour from a column. But what's the difference?
The difference is that when the aes
are set in the original ggplot
, they are inherited by any other geom's that build on top of it. If you specify the aes
only in a geom, it will only be used in that geom. If you use any specific aes
in geom
, they override the settings in ggplot
.
In your example code, in the first instance:
p + geom_point(size = 4)
The size of the points is set to 4, and the aes(wt, mp, colour = 'red')
is inherited from ggplot
. In the second case:
p + geom_point(aes(colour = factor(cyl))
The resulting aes is aes(wt, mpg, colour = factor(cyl)
as the wt
and mpg
are inherited from the ggplot
object, and the colour = factor(cyl)
overwrites the colour = 'red'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With