Align the bar with the drawer in R

I would like to build the distribution of counters using the barplot function in R, and enclose it with boxplot to include information about environments, quartiles and emissions. A not-too-elegant solution for this was found for the histogram and boxes: http://rgraphgallery.blogspot.com/2013/04/rg-plotting-boxplot-and-histogram.html .

There are many places on the Internet where you can find the argument that numerical data should be plotted with bar graphs, while categorical data should be plotted with graphs. My data is numerical, and actually on a ratio scale (since it is a count), but since it is discrete, I need columns with spaces, not columns that touch, which seems to be the only option for the histogram ().

I currently have the following, but bar and boxplot are not perfectly aligned:

set.seed(476372)
counts1 <- rpois(10000,3)
nf <- layout(mat = matrix(c(1,2),2,1, byrow=TRUE),  height = c(3,1))
par(mar=c(3.1, 3.1, 1.1, 2.1))
barplot(prop.table(table(counts1)))
boxplot(counts1, horizontal=TRUE,  outline=TRUE,ylim=c(0,12), frame=F, width = 10)

Here is my question: how can I align them?

+4
source share
2 answers

Another option, similar, but a little more working. This allows you to maintain gaps between the strips:

tbl <- prop.table(table(counts1))
left <- -0.4 + do.call('seq', as.list(range(counts1)))
right <- left + (2 * 0.4)
bottom <- rep(0, length(left))
top <- tbl
xlim <- c(-0.5, 0.5) + range(counts1)

nf <- layout(mat = matrix(c(1,2),2,1, byrow=TRUE),  height = c(3,1))
par(mar=c(3.1, 3.1, 1.1, 2.1))
plot(NA, xlim=xlim, ylim=c(0, max(tbl)))
rect(left, bottom, right, top, col='gray')
boxplot(counts1, horizontal=TRUE,  outline=TRUE, ylim=xlim, frame=F, width = 10)

enter image description here

+5
source

""

ht=hist(counts1,breaks=12,plot = F)
ht$counts=as.numeric(table(counts1))
ht$density=as.numeric(prop.table(table(counts1)))
ht$breaks=as.numeric(names(table(counts1)))
ht$mids=sapply(1:(length(ht$breaks)-1),function(z)mean(ht$breaks[z:(z+1)]))

plot(ht,freq=F,col=3,main="")
boxplot(counts1, horizontal=TRUE,outline=TRUE,ylim=range(ht$breaks), frame=F, col="green1", width = 10)

enter image description here

0

All Articles