问题
Possible Duplicate:
How to plot two histograms together in R?
I want to plot two histograms together, both of them having same x axis units and y axis units. Two histograms are taken from two files, inp1 and inp2. I have tried the following code but it is not working:
x1<-hist(inp1, 120, plot = 0)
x2<-hist(inp2, 120, plot = 0)
hist(x1, x2, 240, plot = 1)
回答1:
The kind of plot you want is not strictly speaking a histogram. You can create something like it, though, using barplot()
with beside=TRUE
:
## Example data
d1 <- rnorm(1000)
d2 <- rnorm(1000, mean=1)
## Prepare data for input to barplot
breaks <- pretty(range(c(d1, d2)), n=20)
D1 <- hist(d1, breaks=breaks, plot=FALSE)$counts
D2 <- hist(d2, breaks=breaks, plot=FALSE)$counts
dat <- rbind(D1, D2)
colnames(dat) <- paste(breaks[-length(breaks)], breaks[-1], sep="-")
## Plot it
barplot(dat, beside=TRUE, space=c(0, 0.1), las=2)
来源:https://stackoverflow.com/questions/11193901/plotting-two-histograms-together