AmirWG
AmirWG

Reputation: 281

abline() is not working with weighted.hist()

So I used the plotrix library to plot a histogram using some weights , the histogram shows up as expected but when I tried a plot the mean as a vertical line it won't show up at all
Here's a snippet of my code:

library("plotrix")
library("zoom")


vals = seq.int(from = 52.5 , to = 97.5 , by = 5)
weights <- c(18.01,18.26,16.42,14.07,11.67,9.19,6.46,3.85,1.71,0.34)/100

mean <- sum(vals*weights)
wh <- weighted.hist(x = vals , w = weights , freq = FALSE)
abline(v = mean)

the abline() seems to work only with the normal hist() function

I am sorry if the question sounds stupid , I am R newbie however I did my research and could not find any helpful info.

Thanks in advance.

Upvotes: 1

Views: 285

Answers (1)

dcarlson
dcarlson

Reputation: 11046

You should provide a sample of your data. Your calculation of the weighted mean is only correct if your weights sum to 1. If they do not, you should use weighted.mean(vals, weights) or sum(vals * weights/sum(weights)). The following example is slightly modified from the one on the weighted.hist manual page (help(weighted.hist)):

vals <- sample(1:10, 300, TRUE)
weights <- (101:400)/100
weighted.hist(vals, weights, breaks=1:10, main="Test weighted histogram")
(mean <- weighted.mean(vals, weights))
# [1] 5.246374

The histogram starts at 1, but this is 0 on the x-axis coordinates so we need to subtract 1 to get the line in the right place:

abline(v=mean-1, col="red")

Histogram

Using your data we need to identify the first boundary to adjust the mean so it plots in the correct location"

wh$breaks[1]
# [1] 52.5
abline(v=mean - wh$breaks[1], col="red")

New Histogram

Upvotes: 2

Related Questions