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
449 views
in Technique[技术] by (71.8m points)

r - How does ggplot calculate its default breaks?

The title is relatively self explanatory. I would like to know how ggplot decides its default breaks (and hence labels).

From the below code, it looks like the method is the same for each geom:

library(ggplot2)

ggplot(data=mtcars,mapping=aes(x=carb,y=hp,fill=as.factor(gear)))+
  geom_bar(stat="identity",position="dodge")

ggplot(data=mtcars,mapping=aes(x=carb,y=hp,fill=as.factor(gear)))+
  geom_point()

Any help would be greatly appreciated

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I had the same question myself, and Google brought me to this SO question, so I thought I'd do a bit of digging.

Suppose we plot

library(ggplot2)
ggplot(mtcars, aes(x = cyl, y = mpg, size = hp)) +
  geom_point() 

which gives us the following plot, and we wish to know how the breaks for mpg (10, 15, ..., 35), cyl (4, 5, ..., 8), and hp (100, 150, ..., 300) are derived.

enter image description here

Focusing on mpg we inspect the code for scale_y_continuous and see that it calls continuous_scale. Then, calling up ?continuous_scale we see, under the description for the trans argument, that

A transformation object bundles together a transform, it's inverse, and methods for generating breaks and labels.

Then, looking up ?scales::trans_new, we see that the default value for the breaks argument is extended_breaks(). Following the trail, we find that scales::extended_breaks calls labeling::extended(rng[1], rng[2], n, only.loose = FALSE, ...). Applying this to our data,

with(mtcars, labeling::extended(range(mpg)[1], range(mpg)[2], m = 5))
# [1] 10 15 20 25 30 35

which is what we observe in the plot. This raises the question of why, despite

with(mtcars, labeling::extended(range(hp)[1], range(hp)[2], m = 5))
# [1]  50 100 150 200 250 300 350

we don't observe 50 and 350 in the legend. My understanding is that the answer is related to https://stackoverflow.com/a/13888731/6455166.


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

...