简体   繁体   中英

How to plot a histogram with a custom distribution?

In an old statistics textbook, I found a table of a distribution of ages for a country's population:

Percent of
 Age    population
------------------
 0-5         8
 5-14       18
14-18        8
18-21        5
21-25        6
25-35       12
35-45       11
45-55       11
55-65        9
65-75        6
75-85        4

I wanted to plot this distribution as a histogram in R, with the age ranges as breaks and the percent of population as the density, but there didn't seem to be a straightforward way to do it. R's hist() function wants you to supply the individual data points, not a pre-computed distribution such as this.

Here's how I went about it.

# Copy original textbook table into two data structures
ageRanges <- list(0:5, 5:14, 14:18, 18:21, 21:25, 25:35, 35:45, 45:55, 55:65, 65:75, 75:85)
pcPop <- c(8, 18, 8, 5, 6, 12, 11, 11, 9, 6, 4)
# Make up "fake" age data points from the distribution described by the table
ages <- lapply(1:length(ageRanges), function(i) {
    ageRange <- ageRanges[[i]]
    round(runif(pcPop[i] * 100, min=ageRange[1], max=ageRange[length(ageRange)-1]), 0)
})
ages <- unlist(ages)
# Use the endpoints of the age class intervals as breaks for the histogram
breaks <- append(0, sapply(ageRanges, function(x) x[length(x)]))
hist(ages, breaks=breaks)

It seems like there has to be a less verbose/hacky way of going about it.

EDIT : FWIW, here's what the resulting histogram looks like:

直方图

This should get what you want:

test <- read.table(textConnection("age popperc
0-5 8
5-14 18
14-18 8
18-21 5
21-25 6
25-35 12
35-45 11
45-55 11
55-65 9
65-75 6
75-85 4"),header=TRUE,stringsAsFactors=FALSE)

midval <- sapply(strsplit(test$age,"-"),function(x) mean(as.numeric(x)))
breakval <- strsplit(test$age,"-")
breakval <- as.numeric(c(sapply(breakval,head,1),tail(unlist(breakval),1)))
hist(rep(midval,test$popperc),breaks=breakval)

在此输入图像描述

You can also define your own object of class histogram and then just plot that if you just want to plot the frequencies not the densities:

# define the histogram object and plot it
histres <- list(
breaks=breakval,
counts=test$popperc,
mids=midval,
xname="ages",
equidist = TRUE
)
class(histres) <- "histogram"
plot(histres)

在此输入图像描述

As said in the comment use a barplot . You can specify width in a barplot

barplot(pcPop,  width = seq(0,85,5),space=0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM