R-Programming - ggplot2 - boxplot问题(varwidth& position_dodge / stat_summary& position_dodge)

时间:2017-07-13 07:40:54

标签: r ggplot2

我目前正在使用ggplot2来显示一些带有箱线图的特征分布。 我可以制作一些简单的箱形图,改变颜色,形状等,但我无法实现结合多种选项的那些。

1°) 我的目的是为男性和女性展示并排的箱形图,可以使用position = position_dodge(width=0.9)来完成。 我希望boxplot的宽度与样本的大小成比例,可以使用var_width=TRUE来完成。 第一个问题:当我将两个选项放在一起时,它不起作用,我收到以下消息:

  

position_dodge需要不重叠的x间隔

使用var_width=TRUEposition_dodge时的Boxplot:

enter image description here

我试图改变剧情的大小,但没有帮助。如果我跳过var_width=TRUE,则框图正确地被躲避。 有没有办法解决这个问题,还是ggplot2的限制?

2°) 此外,我想显示构建箱图的每个样本的大小。 我可以使用stat_summary(fun.data = give.n进行计算,但不幸的是,当箱形图具有相似的位置时,我还没有找到避免数字相互重叠的方法。 我尝试使用hjust& vjust更改数字的位置,但它们似乎有相同的来源,因此无济于事。

当躲避箱图时stats_summary生成的重叠数字:

enter image description here

由于没有标签,我无法使用geom_text,或者我找不到如何将统计信息传递给geom_text的方法。 所以第二个问题是:如何在自己的箱形图上很好地显示每个数字?

这是我的代码:

`library(ggplot2)
# function to get the median of my sample
give.n <- function(x){
  return(c(y = median(x), label = length(x)))
}

plot_boxes <- function(mydf, mycolumn1, mycolumn2) {

  mylegendx <- deparse(substitute(mycolumn1))
  mylegendy <- deparse(substitute(mycolumn2))


  g2  <- ggplot(mydf, aes(x=as.factor(mycolumn1), y=mycolumn2, color=Gender, 
    fill=Gender)) +
  geom_boxplot( data=mydf, aes(x=as.factor(mycolumn1), y=mycolumn2, 
     color=Gender), position=position_dodge(width=0.9), alpha=0.3) +
  stat_summary(fun.data = give.n, geom = "text", size = 3, vjust=1) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_x_discrete(name = mylegendx ) +
  labs(title=paste("Boxplot ", substring(mylegendy, 11), " by ", 
     substring(mylegendx, 11))  , x = mylegendx, y = mylegendy)

  print(g2)


 }

#setwd("~/data")
filename <- "df_stackoverflow.csv"


df_client <- read.csv(file=filename, header=TRUE, sep=";", dec=".")

plot_boxes(df_client, df_client$Client.Class, df_client$nbyears_client)`

数据看起来像这样(来自数据集的小样本 - 20,000行):

Client.Id;Client.Status;Client.Class;Gender;nbyears_client
3;Active;Middle Class;Male;1.38
4;Active;Middle Class;Male;0.9
5;Active;Retiree;Female;0.21
6;Active;Middle Class;Male;0.9
7;Active;Middle Class;Male;3.55
8;Active;Subprime;Male;1.16
9;Active;Middle Class;Male;1.21
10;Active;Part-time;Male;3.38
17;Active;Middle Class;Male;1.83
19;Active;Subprime;Female;5.81
20;Active;Farming;Male;8.99
21;Active;Subprime;Female;6.49
22;Active;Middle Class;Male;1.54
23;Active;Middle Class;Female;2.74
24;Active;Subprime;Male;0.46
25;Active;Executive;Female;0.49
26;Active;Middle Class;Female;3.55
27;Active;Middle Class;Male;3.83
29;Active;Subprime;Female;2.66
30;Active;Middle Class;Male;2.72
31;Active;Middle Class;Female;4.88
32;Active;Subprime;Male;1.46
34;Active;Middle Class;Female;7.16
41;Active;Middle Class;Male;0.65
44;Active;Middle Class;Male;2
45;Active;Subprime;Male;1.13

0 个答案:

没有答案