2014-10-02 75 views
5

我们在课堂设置中使用了dotplots来介绍直方图,因为分档概念对于许多学生来说都很混乱。因此,我们开始与这类似,但更直观的点阵图:使直方图的点坐标Y轴缩放

x <- rnorm(100) 
qplot(x, geom = "bar") 
qplot(x, geom = "dotplot", method="histodot") 

dotplot

因为学生做到这一点对自己的数据,代码需要,无需手动摆弄工作。但是geom_dotplot似乎使用了与geom_bar不同的缩放比例默认值。 y轴不会根据数据进行调整,但似乎仅取决于点的大小。例如:

x <- runif(1000) 
qplot(x, geom = "bar") 
qplot(x, geom = "dotplot", method="histodot") 

dotplot2

我怎样才能让geom_dotplotstat_histodot规模y轴正是因为它会为直方图做,或者通过使用更小的或重叠点来?

+1

在帮助文件中: “由于ggplot2的技术限制,当沿着x轴分级并沿y轴堆叠时,y轴上的数字无意义。您可以像在其中一个示例中那样隐藏y轴,或者手动缩放它以匹配点的数量。“ - 看起来您可能不得不小心操作 – CMichael 2014-10-05 19:52:56

回答

3

我想出了以下解决方案,直到东西适合在页面上缩小了binwidth:

# This function calculates a default binwidth that will work better 
# for the dotplot with large n than the ggplot2 default. 
calculate_smart_binwidth <- function(x, aspect_ratio = 2/3){ 
    x <- as.numeric(x) 
    nbins <- max(30, round(sqrt(length(x))/aspect_ratio)) 
    range <- range(x, na.rm = TRUE, finite = TRUE) 
    if(diff(range) == 0) return(NULL) 
    repeat { 
    message("trying nbins: ", nbins) 
    binwidth <- diff(range)/nbins; 
    highest_bin <- max(ggplot2:::bin(x, binwidth = binwidth)$count); 
    if(highest_bin < aspect_ratio * nbins) return(binwidth) 
    nbins <- ceiling(nbins * 1.03); 
    } 
} 

例子:

x <- runif(1e4) 
qplot(x, geom="dotplot", binwidth=calculate_smart_binwidth(x)) 

plot1

x <- rnorm(1e4) 
qplot(x, geom="dotplot", binwidth=calculate_smart_binwidth(x)) 

plot2

+0

ggplot2 ::: bin不再适用于ggplot版本2.1.0 – 2016-06-07 15:35:51