2015-09-26 117 views
2

由於我想比較幾種分佈,我正在創建相同變量但不同年份的統計圖。但是,y軸的比例變化,因爲頻率的最高點每年都不相同。我想創建直方圖,即所有y軸顯示相同的範圍,即使沒有頻率的那個點。直方圖(計數):y軸的變化比例

更確切地說,在一年內分佈的峯值是30次計數,在另一年中是35次。因爲y軸的比例發生變化,所以在圖中,30與另一次中的35看起來相同。

我試過ylim =(35),但只會導致錯誤「yli​​m無效值」。

謝謝!

+1

你需要給一個下限和上限....嘗試'ylim = C(0,35)'。 (你也可以讓'ggplot'爲你做這些工作......'ggplot(yourdataframe,aes(yourvariable))+ geom_histogram()+ facet_grid(。〜year)' – user20650

回答

7

鍵入?hist到您的控制檯查看文檔。你會看到ylim是「... y值的範圍」。舉例說明如何使用ylimhist(x, freq = FALSE, ylim = c(0, 0.2))。在那裏你可以看到你需要給ylim一個包含下限上限的向量。

對於直方圖,您幾乎總是希望下限爲零(不這樣做通常被認爲是統計學錯誤)。正如在上面的評論中指出的,你可以設置ylim=c(0,35)

樣品與小例子:

#Sets frequencies with which x and y data will appear 
yfreq <- c(1:10, 10:1) #frequencies go up to 10 and down again 
xfreq <- c(1:7, rep(7, times=6), 7:1) #frequencies go up to 7 and down again 

xdata <- rep(1:length(xfreq), times=xfreq) 
ydata <- rep(1:length(yfreq), times=yfreq) 

par(mfrow=c(2,2)) 
hist(ydata, breaks=((0:max(ydata)+1)-0.5), ylim=c(0,10), 
    main="Hist of y with ylim set") 
hist(xdata, breaks=((0:max(xdata)+1)-0.5), ylim=c(0,10), 
    main="Hist of x with ylim set") 
hist(ydata, breaks=((0:max(ydata)+1)-0.5), 
    main="Hist of y without ylim set") 
hist(xdata, breaks=((0:max(xdata)+1)-0.5), 
    main="Hist of x without ylim set") 

Histograms in R with and without setting ylim

所以設置ylim適當地使直方圖工作的側方比較好。

在實踐中,只需找到兩個數據集中的最高峯,然後在ylim中使用它,實際上可以自動完成此操作。你如何做到這一點取決於你是否構造了一個頻率直方圖(這是R如果你的休息是等距離,除非你另有指定)或密度的自動化,但一種方法是創建—但不是繪製—直方圖對象和酌情提取它們的counts或它們的density

#Make histogram object but don't draw it 
yhist <- hist(ydata, breaks=((0:max(ydata)+1)-0.5), plot=FALSE) 
xhist <- hist(xdata, breaks=((0:max(xdata)+1)-0.5), plot=FALSE) 

#Find highest count, use it to set ylim of histograms of counts 
highestCount <- max(xhist$counts, yhist$counts) 
hist(ydata, breaks=((0:max(ydata)+1)-0.5), ylim=c(0,highestCount), 
    main="Hist of y with automatic ylim") 
hist(xdata, breaks=((0:max(xdata)+1)-0.5), ylim=c(0,highestCount), 
    main="Hist of x with automatic ylim") 

#Same but for densities 
highestDensity <- max(xhist$density, yhist$density) 
hist(ydata, breaks=((0:max(ydata)+1)-0.5), 
    freq=FALSE, ylim=c(0,highestDensity), 
    main="Hist of y with automatic ylim") 
hist(xdata, breaks=((0:max(xdata)+1)-0.5), 
    freq=FALSE, ylim=c(0,highestDensity), 
    main="Hist of x with automatic ylim") 

Side by side histograms in R with automatic y limits on frequency or density