Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set xlim in a hist( )plot while showing the full range of the variable in a histogram

Tags:

r

This is a histogram I did in R, please see here: enter image description here

Here is the code I used to get it:

par(mfrow = c(3, 1))
hist(outcome[, 11], main = "Heart Attack", xlim = c(10,20), xlab = "30-day Death Rate")
hist(outcome[, 17], main = "Heart failure", xlim = c(10, 20), xlab = "30-day Death Rate")
hist(outcome[, 23], main = "Pneumonia", xlim = c(10,20), xlab = "30-day Death Rate")

So, how can I modify my codes to get the following graph, please see here: enter image description here

I need to show the full range of of the data on the histogram while having a limited x-axis from 10-20 with only 15 in the middle

like image 262
QY Luo Avatar asked Oct 15 '13 07:10

QY Luo


2 Answers

Something along the lines of this untested code:

par(mfrow = c(3, 1)) #partition the graphics device, 3 stacked
# calculated a common max and min to allow horizontal alignment
# then make 3 histograms (that code seems pretty self-explanatory)
xrange <- range( c(outcome[, 11],outcome[, 17],outcome[, 23]) )
hist(outcome[, 11], main = "Heart Attack", xlim = xrange,xaxt="n", 
         xlab = "30-day Death Rate")
axis(1, at=seq(10,30,by=10), labels=seq(10,30,by=10) )
hist(outcome[, 17], main = "Heart failure", xlim = xrange,xaxt="n", 
         xlab = "30-day Death Rate")
axis(1, at=seq(10,30,by=10), labels=seq(10,30,by=10) )
hist(outcome[, 23], main = "Pneumonia", xlim = xrange, xaxt="n", 
         xlab = "30-day Death Rate")
axis(1, at=seq(10,30,by=10), labels=seq(10,30,by=10) )
like image 195
IRTFM Avatar answered Oct 21 '22 21:10

IRTFM


Have a look at ?axis (and at ?par for the xaxt argument), e.g.:

set.seed(1)
x <- rnorm(100)
## using xaxt="n" to avoid showing the x-axis
hist(x, xlim=c(-4, 4), xaxt="n")
## draw the x-axis with user-defined tick-marks
axis(side=1, at=c(-4, 0, 4))

enter image description here

like image 22
sgibb Avatar answered Oct 21 '22 21:10

sgibb