如何修改ggplot2中boxplot的胡须? [英] How to modify whiskers of a boxplot in ggplot2?

查看:195
本文介绍了如何修改ggplot2中boxplot的胡须?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  library(ggplot2)

p < - ggplot(mtcars,aes(factor(cyl),mpg,fill = factor(am)))
p + geom_boxplot()



我想修改胡须的颜色,例如将其设置为红色。我不认为可以直接< geom_boxplot 这样做,所以这是我的解决方法:

  library(Hmisc)

stat_sum_df < - function(fun,geom =crossbar,...){
stat_summary(fun.data = fun, geom = geom,width = 0.4,...)
}

p + stat_boxplot(geom ='linerange',color =red,position =dodge)+
stat_sum_df(median_hilow,conf.int = 0.5,position =dodge)



线段堆叠在所以下次尝试:

  p + stat_boxplot(geom ='linerange',color =red,position = position_dodge (width = .5))+ 
stat_sum_df(median_hilow,conf.int = 0.5,position = position_dodge(width = .5))



看起来更好,但现在框之间有一个固定的空间(在第一个和第三个绘图上比较cyl = 8)。因为我打算将此代码用于 am 级别的不同级别(当然,在我的真实数据中,它不是 am ),事先并不知道盒子本身有多宽,所以我不能为设置一个固定的宽度 linerange 没有指定固定的宽度的框。



有没有办法选择性地修改 boxplot 的胡须或根据两个方框之间的空间调整 linerange 元素之间的间距?

解决方案

如何将两个盒形图绘制在彼此之上。一个红线,另一个上面没有任何wiskers。

  p + geom_boxplot(color =red)+ geom_boxplot(aes(ymin = .. lower ..,ymax =。 .upper ..))


I'll start with an MWE:

library(ggplot2)

p <- ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(am)))
p + geom_boxplot()

I'd like to modify the colour of the whiskers, e.g., set it to red. I don't think it's possible to do this directly both geom_boxplot, so this is my workaround:

library(Hmisc)

stat_sum_df <- function(fun, geom = "crossbar", ...) {
  stat_summary(fun.data = fun, geom = geom, width = 0.4, ...)
}

p + stat_boxplot(geom = 'linerange', colour = "red", position = "dodge) +
    stat_sum_df("median_hilow", conf.int = 0.5, position = "dodge") 

The line ranges are stacked on top of each other. So next try:

p + stat_boxplot(geom = 'linerange', colour = "red", position = position_dodge(width = .5)) +
   stat_sum_df("median_hilow",conf.int=0.5, position = position_dodge(width = .5))

Looks nicer, but now there is a fixed space between the boxes (compare cyl = 8 on first and third plot). As I'm going to use this code for different number of levels of am (of course in my real data, it's not am), I don't know in advance how wide the boxes themselves will be, so I can't set a fixed width for the linerange without specifying a fixed width for the boxes.

Is there a way either to selectively modify whiskers of a boxplot or to adjust space between linerange elements according to space between the boxes?

解决方案

How about plotting two boxplots on top of each other. One with red lines and a second one on top without any wiskers at all.

p + geom_boxplot(color="red") + geom_boxplot(aes(ymin=..lower.., ymax=..upper..)) 

这篇关于如何修改ggplot2中boxplot的胡须?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆