我目前正在使用 ggplot2 用箱线图显示一些特征分布。我可以生成一些简单的箱线图、更改颜色、形式等,但我无法实现结合多个选项的箱线图。
1°) 我的目的是显示男性和女性的并排箱线图,这可以用position = position_dodge(width=0.9). 我希望箱线图的宽度与样本的大小成正比,这可以通过var_width=TRUE. 第一个问题:当我将两个选项放在一起时,它不起作用,我收到以下消息:
position_dodge 需要不重叠的 x 间隔
当使用箱线图var_width=TRUE和position_dodge在一起:
我试图改变情节的大小,但没有帮助。如果我跳过var_width=TRUE,则箱线图被正确躲避。有没有办法解决这个问题,或者这是ggplot2的限制吗?
2°) 此外,我想显示构建箱线图的每个样本的大小。我可以用 进行计算stat_summary(fun.data = give.n,但不幸的是,当箱线图的位置相似时,我还没有找到避免数字相互重叠的方法。我尝试使用hjust&vjust来更改数字的位置,但它们似乎具有相同的起源,因此无济于事。
stats_summary躲避箱线图时产生的重叠数字:
由于没有标签,我无法使用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)`
Run Code Online (Sandbox Code Playgroud)
数据看起来像这样(来自数据集的小样本 - 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
Run Code Online (Sandbox Code Playgroud)