Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to hist()-like bars in plot()

I would like to add a histogram of a distribution of a variable on an already generated plot() window. This script is heavily customized and I can only add to it. I can't use hist() to plot. X-axis is on an continuous scale, Y-scale is probability [0,1] (edit: One of the y-axis is probability the other is continuous). How can I add bars to represent the distribution of this variable on the already generated plot()? Base-R only please

What I have done so far is plot() and then do the distribution with lines(hist()$breaks, hist()$density, type="h") which however gives me only lines but not the box-like bars of hist()

From what I understand boxplot() won't help and barplot() requires factors not continuous scale variables (like I have).

UPDATE: The hist(...,add=T) option does not work for me. I would like to be as flexible as with in the line() solution (thus able to transform x and y vectors), but instead of lines to draw boxes. Any ideas?

like image 828
ECII Avatar asked Oct 24 '25 06:10

ECII


2 Answers

Your idea with lines() could work but then you have to use mids instead of breaks for x values and also make your lines wider with argument lwd=. Argument lend="butt" will ensure that lines are not rounded.

set.seed(123)
x<-rnorm(100)
zz<-hist(x)

plot(x=c(-2.5,2.5),y=c(0,1),type="n")
lines(zz$mids, zz$density, type="h",lwd=50,lend="butt")

enter image description here

Update

To get something like boxes (as those are lines you can't change just fill of them) you can plot two lines above each other with different colors and different width, and change all density values by small amount.

plot(x=c(-2.5,2.5),y=c(0,1),type="n")
lines(zz$mids, zz$density, type="h",lwd=50,lend="butt")
lines(zz$mids, zz$density-0.005, type="h",lwd=48,lend="butt",col="white")

enter image description here

like image 142
Didzis Elferts Avatar answered Oct 26 '25 18:10

Didzis Elferts


You can simply add the hist() plot to already existing plot using add = TRUE. Don't forget to use freq = FALSE to say you want the probability scale, not the count scale.

set.seed(123)
x<-rnorm(100)

plot(x, exp(x)/(1+exp(x)), col = "green") # some plot
hist(x, freq = FALSE, add = TRUE)

EDIT: If you need to perform any manipulation on the computed histogram, you can replace the hist call by splitting it into computation and the plotting itself, which is done using rect() (see the source code of plot.histogram):

h <- hist(x, plot = FALSE) # computation
rect(h$breaks[-length(h$breaks)], 0, h$breaks[-1], h$intensities) # plotting

enter image description here

like image 33
Tomas Avatar answered Oct 26 '25 19:10

Tomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!