简体   繁体   中英

ggplot difference in aes()

Consider a plot of a df in ggplot:

ggplot(data = df, aes(x=X,y=Y)) +
geom_point(aes(color=Trial)) 

The variable Trial in this case is a factor . Could someone explain me what is the difference between plotting the factor inside the geom_point function and outside as in the case below :

ggplot(data = df, aes(x=X,y=Y,color=Trial))

Here is a sample of the df :

structure(list(Sample = c("GID7173723", "GID4878677", "GID88208", 
"GID346403", "GID268825", "GID7399578"), Trial = structure(c(4L, 
6L, 5L, 5L, 5L, 6L), .Label = c("ES1-5", "ES6-13", "ES14-26", 
"ES27-38", "SA1-13", "SA14-25"), class = "factor"), X = c(8.68082802271727, 
-52.0699224029511, -23.9642181294958, 53.3466936371821, -85.064856918598, 
33.4668785456285), Y = c(-35.3997039478218, 46.2365967946906, 
-42.8190962627021, 24.245938561458, 95.9865691321666, 25.6522750117316
), Z = c(12.3326491737533, -24.7722861720316, -11.7262667337085, 
-43.0492006899678, -51.7268052275685, 49.6715770397554)), row.names = c(NA, 
6L), class = "data.frame")

I suppose you meant

ggplot(data = df, aes(x = X, y = Y)) +
  geom_point(aes(color = Trial))

versus

ggplot(data = df, aes(x = X, y = Y, color = Trial)) +
  geom_point()

rather than just the first line, without geom_point . Not including geom_point clearly would not give any points regardless of specified aesthetics.

Now those two code excerpts, as you can see, give identical results in this case. More generally, the difference would be in that in the first case you set the color aesthetic only for geom_point , while in the second case it is set globally. That is, you could use

ggplot(data = df, aes(x = X, y = Y, color = Trial)) +
  geom_point() + geom_line()

在此处输入图片说明

and now both geoms would use the same color aesthetic. On the other hand,

ggplot(data = df, aes(x = X, y = Y)) +
  geom_point(aes(color = Trial)) + geom_line()

在此处输入图片说明

would give black lines. Also note that as a side effect lines are also grouped by Trial .

In this case there is no difference in the "aesthetic mapping" section. The actrual problem is that every ggplot object need at least one "geometric layer" to work functionally. In other words, you need to tell ggplot object to use point to represent the X and Y value by the coordinate of these points, which is exactly what function geom_point() do.

So

ggplot(data = df, aes(x = X, y = Y)) + geom_point(aes(color = Trial))

p1

And

ggplot(data = df, aes(x = X, y = Y, color = Trial)) + geom_point()

p2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM