Search code examples
rhistogrambin

Plot specific bins in histogram in r


I have data that looks like this:

  > data1415$Lön_utv
 [1]  2.500000  2.499134 11.979167  2.606635  2.299856  2.300086  2.399993  2.499763  2.499134  5.000000
[11]  2.499134  3.213068  3.497202  6.666667  3.467406  2.493373  3.976479  2.501996  2.499356  3.286318
[21]  2.503582  2.503582  2.499356  2.499356  2.499356  2.499356  2.459016  2.505516  2.499356  2.504103
[31]  2.503582  2.459016  2.503582  2.544523  5.660377  2.501949  2.503966  2.499332  2.358491  3.113852
[41]  2.499356  2.499332  2.499356  2.459016  2.499332  2.941176  2.499356  2.499356  2.499356  2.499356
[51]  3.400695  6.512312  2.504863  2.499356  2.499356  6.516168  2.503966  2.503582  3.400695  2.358491
[61]  3.899955  7.525569  2.503582  2.499236  2.283105  2.499332  2.941176  2.499356  2.503582  6.335204
[71]  5.216359  2.501495  5.936073  2.503966  2.358491  7.152135  6.072188  2.502615  6.063219 10.193115
[81]  2.504279  2.503582  2.501231  2.505728  2.500144  3.658113  2.502452  2.941176  5.000000  2.500818
[91]  2.499236  8.054799  2.500144  1.672703  2.941176  2.162162  6.072188  2.941176  3.251276  2.941176
[101]  2.501231  2.500818  7.397407  2.162162  4.860217  2.941176  2.162162  2.162162  2.162162  2.501361

If I cut the data I get this:

> c2 <- cut(data1415$Lön_utv, breaks = c(0:8, 20), include.lowest=TRUE)
> table(c2)
c2
[0,1]  (1,2]  (2,3]  (3,4]  (4,5]  (5,6]  (6,7]  (7,8] (8,20] 
 0      1     79     11      1      5      7      3      3 

I want to create a histogram with bins 0-1, 1-2, 2-3 and so forth. My problem is I want the x-axis to be no wider than say about 8. That would exclude all values above 8 so I would like the rightmost bin to include all values above 8. I´ve tried something like

hist(data1415$Lön_utv, breaks = c(0:8, 20), right=FALSE)

But can´t figure out how to make the x-axis no longer than 8 and still get a "top" bin with all values above.


Solution

  • As said in the comments, you need a barplot for this using bins. Assuming that our numerical variable is in 'value', we can calculate the bins:

    dat$bin <- cut(dat$value, breaks=c(0:8,20))
    

    Then using ggplot, we can plot the counts:

    ggplot(dat, aes(x=bin)) + geom_bar()
    

    To get percentages, we can have ggplot calculate those for us. We do need to add a percentage scale to it. And to avoid confusion, have the axis go from 0 to 100%.

    ggplot(dat, aes(x=bin)) + 
      geom_bar(aes(y=..count../sum(..count..))) + 
      scale_y_continuous(limits=c(0,1),labels=scales::percent)