2014-10-02 76 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