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

r - How can I add the 5 quantiles of the quantile function to a boxplot in ggplot2 with one variable?

So i want to add the min, 25.pc, median, 75. pc and max to a boxplot in ggplot with one variable. For the purpose of an example I will describe the problem with the mtcars dataset. I saw another thread with a similar question: annotate boxplot in ggplot2 and I tried to replicate the answer from the user eipi10. But the process failed with just one variable. Somehow the quantile function gives other output. It shows the value of each single data point in the variable in the plot.

library(ggplot2)
ggplot(mtcars, aes(x = mpg)  +
  geom_boxplot(width = 0.6) +
  stat_summary(geom = "text", fun = quantile,
               aes(label = ..x.., y = 0.1), size = 3.5)

even if I change the probs argument from the quantile function and give it to the stat_summary() function it displays weird results.

question from:https://stackoverflow.com/questions/65844453/how-can-i-add-the-5-quantiles-of-the-quantile-function-to-a-boxplot-in-ggplot2-w

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

1 Reply

0 votes
by (71.8m points)

The issue is that the quantiles are computed for y instead of the variable which is mapped on x. The reason is that stat_summary makes a guess about which variable to use for computing the quantiles but fails in your case as both x and y=0.5 are numeric (see the section Orientation in ?stat_summary). To prevent that you have to tell stat_summary which variable or axis to use for the computations of the quantiles by setting the orientation argument. Or you could add an auxiliary categorical variable by mapping e.g "1" on y. In that case stat_summary will by default pick the numeric variable (i.e. the one mapped on x) to compute the quantiles.

library(ggplot2)

ggplot(mtcars, aes(x = mpg, y = "1"))  +
         geom_boxplot(width = 0.6) +
         stat_summary(geom = "text", fun = quantile,
                      aes(label = ..x.., y = 1.5), size = 3.5)

ggplot(mtcars, aes(x = mpg))  +
  geom_boxplot(width = 0.6) +
  stat_summary(geom = "text", fun = quantile,
               aes(label = ..x.., y = 0.5), size = 3.5, orientation = "y")


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

...