2016-06-10 100 views
5

當用colorfill自變量呼叫geom_histogram()時,ggplot2會混淆繪製整個x軸範圍,從而無法在視覺上區分低值和零值。當使用ggplot2時,我可以設置直方圖條的顏色而不會掩蓋低值嗎?

運行下面的代碼:

ggplot(esubset, aes(x=exectime)) + geom_histogram(binwidth = 0.5) + 
theme_bw() + scale_x_continuous(breaks=seq(0,20), limits=c(0,20)) 

將導致

a histogram w/o color attributes

這是視覺上非常吸引人。爲了解決這個問題,我想改用

ggplot(esubset, aes(x=exectime)) + geom_histogram(binwidth = 0.5, 
colour='black', fill='gray') + theme_bw() + 
scale_x_continuous(breaks=seq(0,20), limits=c(0,20)) 

這將導致

a histogram with color attributes

的問題是,我不會有區別的方式exectime是否包含過去的10個值,例如,少數情況下的12會隱藏在橫跨整個x軸的水平線後面。

+0

你介意使用logaritmic縮放嗎? –

+0

也許手動進行聚合?你正在用'limits'參數引起這種行爲。 – hrbrmstr

回答

5

使用coord_cartesian而不是scale_x_continuouscoord_cartesian設置軸範圍而不影響數據繪圖的方式。即使使用coord_cartesian,仍然可以使用scale_x_continuous來設置breaks,但coord_cartesian將覆蓋對數據繪製方式的任何影響scale_x_continuous

在下面的假數據中,請注意我添加了一些非常小的條形圖的數據。

set.seed(4958) 
dat = data.frame(value=c(rnorm(5000, 10, 1), rep(15:20,1:6))) 

ggplot(dat, aes(value)) + 
    geom_histogram(binwidth=0.5, color="black", fill="grey") + 
    theme_bw() + 
    scale_x_continuous(limits=c(5,25), breaks=5:25) + 
    ggtitle("scale_x_continuous") 

ggplot(dat, aes(value)) + 
    geom_histogram(binwidth=0.5, color="black", fill="grey") + 
    theme_bw() + 
    coord_cartesian(xlim=c(5,25)) + 
    scale_x_continuous(breaks=5:25) + 
    ggtitle("coord_cartesian") 

enter image description here

正如可以在上面的曲線圖看到,如果有與所述數據範圍內計數= 0 箱,ggplot將添加零線,即使coord_cartesian。這使得難以在高度= 1的15處看到酒吧。您可以與lwd參數(「線寬」)的邊界薄的多,小酒吧會越來越模糊:

ggplot(dat, aes(value)) + 
    geom_histogram(binwidth=0.5, color="black", fill="grey", lwd=0.3) + 
    theme_bw() + 
    coord_cartesian(xlim=c(5,25)) + 
    scale_x_continuous(breaks=5:25) + 
    ggtitle("coord_cartesian") 

enter image description here

另外一個選擇是預總結使用geom_bar數據和情節爲了獲得條之間的空間,從而避免需要對邊界線,以紀念吧邊緣:

library(dplyr) 
library(tidyr) 
library(zoo) 

bins = seq(floor(min(dat$value)) - 1.75, ceiling(max(dat$value)) + 1.25, 0.5) 

dat.binned = dat %>% 
    count(bin=cut(value, bins, right=FALSE)) %>% # Bin the data 
    complete(bin, fill=list(n=0)) %>%    # Restore empty bins and fill with zeros 
    mutate(bin = rollmean(bins,2)[-length(bins)]) # Convert bin from factor to numeric with value = mean of bin range 

ggplot(dat.binned, aes(bin, n)) + 
    geom_bar(stat="identity", fill=hcl(240,100,30)) + 
    theme_bw() + 
    scale_x_continuous(breaks=0:21) 

enter image description here

相關問題