geom_dotplot点布局与组

时间:2016-09-07 17:27:29

标签: r ggplot2

我想要创建的点图如下所示。这些点已经使用了几种不同的选项进行了布局。

require(data.table)
require(ggplot2)

set.seed(10000)
n <- 300

dt <- data.table(Duration=sample(100:800,n,replace=T), EndType=round(runif(n,min=.4)), Group=sample(c("GrpA","GrpB"),n,replace=T))
dt <- rbind(dt, dt[, -c("Group"), with=F][, Group:="All"])
dt[, ":="(Group=factor(Group, levels=c("All","GrpA","GrpB"), ordered=T), EndType=factor(EndType, levels=c(0,1)))]

#option 1 - creates space between dots which are filled and not filled
g <- ggplot(dt, aes_string(x="Group", y="Duration")) + coord_flip() +
    geom_boxplot(aes(ymin=..lower.., ymax=..upper..), fatten=1.1, lwd=.1, outlier.shape=NA) + 
    geom_dotplot(aes(fill=EndType), binaxis="y", stackdir="center", stackgroups=T, method="histodot", binwidth=15, dotsize=.5) +
    scale_fill_manual(values=c("white","black"))
print(g)

#option 2 - extends to the other bar when there are many of one type
g <- ggplot(dt, aes_string(x="Group", y="Duration")) + coord_flip() +
    geom_boxplot(aes(ymin=..lower.., ymax=..upper..), fatten=1.1, lwd=.1, outlier.shape=NA) + 
    geom_dotplot(data=dt[EndType==1], aes(fill=EndType), fill="black", binaxis="y", stackdir="up", method="histodot", binwidth=15, dotsize=.5) +
    geom_dotplot(data=dt[EndType==0], aes(fill=EndType), fill="white", binaxis="y", stackdir="down", method="histodot", binwidth=15, dotsize=.5)
print(g)

是否有一种方法来布置点(黑色和白色),使它们像选项2一样在一起,但是在线上居中?

选项1 enter image description here

选项2 enter image description here

> sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggplot2_2.1.0    data.table_1.9.7

loaded via a namespace (and not attached):
[1] labeling_0.3     colorspace_1.2-6 scales_0.4.0     plyr_1.8.4       gtable_0.2.0    
[6] Rcpp_0.12.6      grid_3.3.1       digest_0.6.10    munsell_0.4.3   

1 个答案:

答案 0 :(得分:4)

我想你可能遇到过一个bug。我不确定为什么在你的第一个选项中堆叠组是错误的。也许其他人可以权衡。您可能想要搜索并报告此问题here

以下是 的快速解决方法,而不是我们使用方面的一个轴上的多个点图:

ggplot(dt, aes_string(x=1, y="Duration")) + coord_flip() +
  geom_boxplot(aes(ymin=..lower.., ymax=..upper..), fatten=1.1, lwd=.1, outlier.shape=NA) + 
  geom_dotplot(aes(fill=EndType), binaxis="y", stackdir="center", stackgroups=T, method="histodot", binwidth=15, dotsize=.5) +
  scale_fill_manual(values=c("white","black")) +
  facet_grid(Group~.)

enter image description here