直方图(计数):更改y轴的比例

时间:2015-09-26 19:55:39

标签: r scale histogram

由于我想比较几个分布,我正在创建相同变量但不同年份的组织图。但是,y轴的比例会发生变化,因为频率的最高点每年都不同。我想创建直方图,其中所有y轴显示相同的范围,即使该点没有频率。

更确切地说,在一年中,分布的峰值是30个计数,在另一年中它是35,在图表上,30个看起来与另一个中的35个相同,因为y轴的比例发生变化。 / p>

我试过ylim =(35),但这只会导致错误“yli​​m的值无效”。

谢谢!

1 个答案:

答案 0 :(得分:9)

在控制台中输入?hist以查看文档。您会看到ylim用于" 值"的范围。有一个示例显示了如何使用ylim hist(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是等距的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