簡體   English   中英

R - 具有共享/相同 x 和 y 軸的直方圖

[英]R - Histograms with shared/same x and y axes

我想繪制兩個直方圖,其中 x 和 y 范圍對於兩者都相同。 閱讀一些帖子后,我的解決方案是使用 ggplot2、geom_histogram 兩次。 我第一次創建繪圖而不為每個感興趣的數據集繪圖,目的是在所有感興趣的繪圖中獲得最大的 y/count 和 x 軸值。 例如,有兩個圖,如果第一個 ymax_1 = 10 另一個 ymax_2 = 15,則兩個圖的 y 軸范圍至少從 0 到 15。 同樣適用於 x 軸。

在這個圖之后,我取 ymax/xmax 值並像以前一樣繪制直方圖,並添加 xlim(0, xmax) 和 ylim(0, ymax)。 但是,當我這樣做時,計數會發生變化。 更具體地說,在我沒有指定任何 xlim/ylim 的第一個圖中,我從 ggplot_build( ggplot(...) + geom_histogram(...)) ymax = 2000 得到但是當我第二次使用 xlim 時我得到ymax = 4000。不過,從第一個圖中我有 ymax = 2000,因此第二次沒有正確繪制直方圖。 當我刪除 xlim 選項時,我得到了相同的結果。

xlim 選項如何以及為什么會影響計數? 我希望這很清楚。

df = read.table( paste( path, f, sep = "/"), header = TRUE, fill = TRUE, sep = ",", stringsAsFactors = TRUE)
measure = colnames( df)[ 7]
combs = unique( df[, c( 'A', 'B', 'C')])
# order combs in specific order to get a specific sequence of plots
combs = combs[ with( combs, order( B, C, A)), ]
bns = lst()
xmxs = lst()
ymxs = lst()
for( j in seq( 1, length( combs[ , 1]), 2)) {
 if( combs[ j, 2] == combs[ j, 3]) {
  next
 }
 tmp = subset( df, A == combs[ j, 1] & B == combs[ j, 2] & C == combs[ j, 3], select = c( measure))
 # Freedman – Diaconis rule, "On the histogram as a density estimator: L2 theory"
 bw = 2 * IQR( tmp[ , 1]) / ( length( tmp[ , 1])^(1/3))
 bns[[ j]] = ceiling( ( max( tmp[ , 1]) - min( tmp[ , 1])) / bw)

 plots[[ j]] = ggplot( tmp, aes_string( measure)) + geom_histogram( bins = bns[[ j]], aes( fill = ..count..))
 histg = ggplot_build( plots[[ j]])$data[[ 1]]
 ymxs[[ j]] = max( histg$count)
 xmxs[[ j]] = max( histg$x)

 tmp = subset( df, A == combs[ j + 1, 1] & B == combs[ j + 1, 2] & C == combs[ j + 1, 3], select = c( measure))
 # Freedman – Diaconis rule, "On the histogram as a density estimator: L2 theory"
 bw = 2 * IQR( tmp[ , 1]) / ( length( tmp[ , 1])^(1/3))
 bns[[ j + 1]] = ceiling( ( max( tmp[ , 1]) - min( tmp[ , 1])) / bw)

 plots[[ j + 1]] = ggplot( tmp, aes_string( measure)) + geom_histogram( bins = bns[[ j + 1]], aes( fill = ..count..))
 histg = ggplot_build( plots[[ j + 1]])$data[[ 1]]
 ymxs[[ j + 1]] = max( histg$count)
 xmxs[[ j + 1]] = max( histg$x)
 if( ymxs[[ j]] > ymxs[[ j + 1]]) {
  ymxs[[ j + 1]] = ymxs[[ j]]
 }
 else {
  ymxs[[ j]] = ymxs[[ j + 1]]
 }
 if( xmxs[[ j]] > xmxs[[ j + 1]]) {
  xmxs[[ j + 1]] = xmxs[[ j]]
 }
 else {
  xmxs[[ j]] = xmxs[[ j + 1]]
 }
}
pplots = lst()
for( j in 1 : length( combs[ , 1])) {
 if( combs[ j, 2] == combs[ j, 3]) {
  next
 }
 tmp = subset( df, A == combs[ j, 1] & B == combs[ j, 2] & C == combs[ j, 3], select = c( measure))
 avg = sprintf( "%.2f", mean( tmp[ , 1]))
 stdv = sprintf( "%.2f", std( tmp[ , 1]))
 count = length( tmp[ , 1])
 entities[[ j]] = paste( combs[ j, 1], " ", combs[ j, 2], " vs ", combs[ j, 3])
pplots[[ j]] = ggplot( tmp, aes_string( measure)) +
 geom_histogram( bins = bns[[ j]], aes( fill = ..count..)) +
 # xlim( 0, 1.2*xmxs[[ j]]) +
 # ylim( 0, 1.2*ymxs[[ j]]) +
 ggtitle( bquote( atop( paste( .(entities[[ j]])), paste( mu, " = ", .( avg), ", ", sigma, " = ", .( stdv), ", #cells = ", .( count), sep = " ")))) +
 theme( plot.title = element_text( size = 20), axis.text = element_text( size = 12), axis.title = element_text( size = 15))
 }

 # plot every two plots because the Reference.Population is the same
 for( j in seq( 1, length( plots), 2)) {
 fileext = str_remove_all( entities[[ j]], 'N')
 filename_hi = paste( gsub( '.{4}$', '', f), "_distribution_", fileext, ".png", sep = "")
 png( filename = paste( path, filename_hi, sep = "/"))
 grid.draw( rbind( ggplotGrob( pplots[[ j]]), ggplotGrob( pplots[[ j + 1]]), size = "last"))
 dev.off()
 }

因此,在上面的代碼中, plots包含我從中獲取 y、x 軸的最小值和最大值的初始圖,而pplots包含我最終使用xlim/ylim選項繪制的圖。 然而,例如,

max( plots[[ 8]]$data[[ 1]]$count) != max( plots[[ 8]]$data[[ 1]]$count)

當我使用xlim選項時。 第一個給出1947 ,另一個給出我的數據4529

謝謝

作為您閱讀的其他帖子的替代方案,我建議將數據集合並為一個,並對它們進行分面。 為此,您需要選擇要繪制直方圖的列,並添加一列指示從中提取數據的數據集。

在這個例子中,我將結合iris$Sepal.Lengthmtcars$disp

range(mtcars$disp)
# [1]  71.1 472.0
range(iris$Sepal.Length)
# [1] 4.3 7.9

由於這些示例數據是如此不同,我將縮放一個,以便繪圖看起來更具可比性……但足夠不同,以便您可以看到軸是共享的。

400 * (range(iris$Sepal.Length) - 4)
# [1]  120 1560

如果您的數據需要這樣的東西,請交給您。

從這里,結合相關字段:

combined_dat <- rbind(
  cbind.data.frame(src = "iris Sepal.Length", val = 400 * (iris[, c("Sepal.Length")] - 4)),
  cbind.data.frame(src = "mtcars disp*", val = mtcars[, c("disp")])
)

head(combined_dat)
#                 src val
# 1 iris Sepal.Length 440
# 2 iris Sepal.Length 360
# 3 iris Sepal.Length 280
# 4 iris Sepal.Length 240
# 5 iris Sepal.Length 400
# 6 iris Sepal.Length 560

tail(combined_dat)
#              src   val
# 177 mtcars disp* 120.3
# 178 mtcars disp*  95.1
# 179 mtcars disp* 351.0
# 180 mtcars disp* 145.0
# 181 mtcars disp* 301.0
# 182 mtcars disp* 121.0

然后劇情。

ggplot(combined_dat, aes(val)) +
  geom_histogram() +
  facet_wrap(~ src, ncol = 1)
# `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

組合直方圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM