我们在教室环境中使用点图来介绍直方图,因为分组概念让许多学生感到困惑.所以我们从相似但更直观的dotplot开始:
x <- rnorm(100)
qplot(x, geom = "bar")
qplot(x, geom = "dotplot", method="histodot")
Run Code Online (Sandbox Code Playgroud)

因为学生在他们自己的数据上执行此操作,所以代码需要在没有手动调整的情况下工作.但是,geom_dotplot似乎使用不同的缩放默认值geom_bar.y轴不随数据调整,但似乎仅取决于点的大小.例如:
x <- runif(1000)
qplot(x, geom = "bar")
qplot(x, geom = "dotplot", method="histodot")
Run Code Online (Sandbox Code Playgroud)

我怎样才能让geom_dotplot与stat_histodot规模y轴正是因为它会为直方图做,或者通过使用更小的或重叠点来?
我想出了以下解决方法,可以缩小 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);
}
}
Run Code Online (Sandbox Code Playgroud)
例子:
x <- runif(1e4)
qplot(x, geom="dotplot", binwidth=calculate_smart_binwidth(x))
Run Code Online (Sandbox Code Playgroud)

x <- rnorm(1e4)
qplot(x, geom="dotplot", binwidth=calculate_smart_binwidth(x))
Run Code Online (Sandbox Code Playgroud)
