Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

r - Why is stat = "identity" necessary in geom_bar in ggplot?

From this question we see a simple geom_line in the answer.

library(dplyr)
BactData %>% filter(year(Date) == 2017) %>% 
  ggplot(aes(Date, Svartediket_CB )) + geom_line()

If we change geom_line to geom_bar we may expect to see a bar plot, but instead

Error: stat_count() must not be used with a y aesthetic.

But it works if we add stat = "identity", like so

library(dplyr)
BactData %>% filter(year(Date) == 2017) %>% 
  ggplot(aes(Date, Svartediket_CB )) + geom_bar(stat = "identity")

Why doesn't geom_bar work without stat = "identity" - i.e. what is the purpose of stat = "identity"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two layers that are closely related: geom_bar() and geom_col(). The key difference is how they aggregate the data by default.

For geom_bar(), the default behavior is to count the rows for each x value. It doesn't expect a y-value, since it's going to count that up itself -- in fact, it will flag a warning if you give it one, since it thinks you're confused. How aggregation is to be performed is specified as an argument to geom_bar(), which is stat = "count" for the default value.

If you explicitly say stat = "identity" in geom_bar(), you're telling ggplot2 to skip the aggregation and that you'll provide the y values. This mirrors the natural behavior of geom_col() below.

In the case of geom_col(), it won't try to aggregate the data by default. From the docs, "geom_col() uses stat_identity(): it leaves the data as is". So, it expects you to already have the y values calculated and to use them directly. And geom_col() doesn't have an argument to change that behavior - it's always going to plot your y values that you provide, and you need to provide them.

If you have y values, you could use either syntax, but I find geom_col() more direct.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...