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

r - Boxplot, how to match outliers' color to fill aesthetics?

I am trying to match boxplot's outliers color to the fill color which is set by aesthetic (scale_colour_discrete).

Here is an example.

m <- ggplot(movies, aes(y = votes, x = factor(round(rating)),
    fill=factor(Animation)))
m + geom_boxplot() + scale_y_log10()

This generates plot below. How do I change those black dots to be reddish/greenish colors used in the body? outlier.colour option of the boxplot seems to pick one colour across, and not as aesthetic, if I understand correctly. I dont mind using colour aesthetics if that helps.

Original Version


Edit:

Adapted this solution (Changing whisker definition in geom_boxplot). The horizontal dodging is reset by stats_summary and I couldn't figure out how to get it back. I'd ptobably drop outliers and stretch whiskers as needed since I know how now.

# define the summary function
f <- function(x) {
  r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}
# define outlier function, beyound 5 and 95% percentiles
o <- function(x) {
  subset(x, x < quantile(x,probs=c(0.05))[1] | quantile(x,probs=c(0.95))[1] < x)
}

m <- ggplot(movies, aes(y = votes, x = factor(round(rating)),
    colour=factor(Animation)))
m <- m + stat_summary(fun.data=f, geom='boxplot')
m <- m + stat_summary(fun.y=o, geom='point', aes(colour=factor(Animation)))
m + scale_y_log10()

Failed attempt

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As @koshke said, having the outliers colored like the lines of the box (not the fill color) is now easily possible by setting outlier.colour = NULL:

m <- ggplot(movies, aes(y = votes, x = factor(round(rating)),
    colour = factor(Animation)))
m + geom_boxplot(outlier.colour = NULL) + scale_y_log10()

boxplot with coloured outliers

  • outlier.colour must be written with "ou"
  • outlier.colour must be outside aes ()

I'm posting this as a late answer because I find myself looking this up again and again, and I also posted it for the related question Coloring boxplot outlier points in ggplot2?.


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

...