如何通过R中的x值缩放直方图上的y轴?

时间:2010-10-13 09:14:17

标签: r scale histogram

我有一些代表粒子大小的数据。我想将每个分级大小的粒子的频率绘制为直方图,但是要缩放频率但是缩放粒子的大小(因此它表示该大小的总质量。)

我可以很好地绘制直方图,但我不确定如何按每个bin的X值缩放Y轴。

e.g。如果我在40-60箱中有10个粒子,我希望Y轴值为10 * 50 = 500。

3 个答案:

答案 0 :(得分:3)

如果你真的想使用每个bin的中点作为缩放因子:

d<-rgamma(100,5,1.5) # sample
z<-hist(d,plot=FALSE) # make histogram, i.e., divide into bins and count up
co<-z$counts # original counts of each bin
z$counts<-z$counts*z$mids # scaled by mids of the bin

plot(z, xlim=c(0,10),ylim=c(0,max(z$counts))) # plot scaled histogram
par(new=T)
plot(z$mids,co,col=2,  xlim=c(0,10),ylim=c(0,max(z$counts))) # overplot original counts

相反,如果您想将每个采样点的实际值用作比例因子:

d<-rgamma(100,5,1.5)
z<-hist(d,plot=FALSE)
co<-z$counts # original counts of each bin
z$counts<-aggregate(d,list(cut(d,z$breaks)),sum)$x # sum up the value of data in each bin

plot(z, xlim=c(0,10),ylim=c(0,max(z$counts))) # plot scaled histogram
par(new=T)
plot(z$mids,co,col=2,  xlim=c(0,10),ylim=c(0,max(z$counts))) # overplot original counts

答案 1 :(得分:3)

你最好使用条形图来表示箱子面积的总质量(即高度给出计数,宽度给出质量):

sizes <- 3:10   #your sizes    
part.type <- sample(sizes, 1000, replace = T)  #your particle sizes  

count <- table(part.type)  
barplot(count, width = size)  

如果您的粒子大小不同,您应首先将范围缩小到适当的间隔数,以便创建part.type factor:

part <- rchisq(1000, 10)  
part.type <- cut(part, 4)  

count <- table(part.type)  
barplot(count, width = size)  

如果感兴趣的数量仅为总质量。然后,适当的图是圆点图。与大量尺寸的条形图相比,它也更清晰:

part <- rchisq(1000, 10)
part.type <- cut(part, 20)

count <- table(part.type)
dotchart(count)

用垃圾箱代表总质量会产生误导,因为垃圾箱的面积毫无意义。

答案 2 :(得分:0)

只需隐藏轴并根据需要重新绘制它们。

# Generate some dummy data
datapoints <- runif(10000, 0, 100)

par (mfrow = c(2,2))

# We will plot 4 histograms, with different bin size
binsize <- c(1, 5, 10, 20)

for (bs in binsize)
    {
    # Plot the histogram. Hide the axes by setting axes=FALSE
    h <- hist(datapoints, seq(0, 100, bs), col="black", axes=FALSE, 
        xlab="", ylab="", main=paste("Bin size: ", bs))
    # Plot the x axis without modifying it
    axis(1)
    # This will NOT plot the axis (lty=0, labels=FALSE), but it will return the tick values
    yax <- axis(2, lty=0, labels=FALSE)
    # Plot the axis by appropriately scaling the tick values
    axis(2, at=yax, labels=yax/bs)
    }