1

I asked a question before, but now I would like to know how do I put the labels above the bars.

post old: how to create a frequency histogram with predefined non-uniform intervals?

dataframe <- c (1,1.2,40,1000,36.66,400.55,100,99,2,1500,333.45,25,125.66,141,5,87,123.2,61,93,85,40,205,208.9)

Upatdate

Update

Following the guidance of the colleague I am updating the question.

I have a data base and I would like to calculate the frequency that a given value of that base appears within a pre-defined range, for example: 0-50, 50-150, 150-500, 500-2000.

in the post(how to create a frequency histogram with predefined non-uniform intervals?) I managed to do this, but I don't know how to add the labels above the bars. I Tried:

barplort (data, labels = labels), but it didn't work.

I used barplot because the post recommended me, but if it is possible to do it using ggplot, it would be good too.

wesleysc352
  • 579
  • 1
  • 8
  • 21
  • Do the answers to [this question](https://stackoverflow.com/questions/9317948/how-to-label-histogram-bars-with-data-values-or-percents-in-r) help? – eipi10 Nov 29 '20 at 06:08
  • 1
    Please don't tag `rstudio` for the posts which have nothing to do with R Studio IDE. – Ronak Shah Nov 29 '20 at 07:48
  • If the question @eipi10 linked doesn't help, please add more details and a reproducible example of your visualisation (so this question is self-contained) – stragu Nov 29 '20 at 12:46
  • @stragu i edited issue – wesleysc352 Nov 29 '20 at 16:27

1 Answers1

3

Based on the answer to your first question, here is one way to add a text() element to your Base R plot, that serves as a label for each one of your bars (assuming you want to double-up the information that is already on the x axis).

data <- c(1,1.2,40,1000,36.66,400.55,100,99,2,1500,333.45,25,125.66,141,5,87,123.2,61,93,85,40,205,208.9)
# Cut your data into categories using your breaks
data <- cut(data, 
            breaks = c(0, 50, 150, 500, 2000),
            labels = c('0-50', '50-150', '150-500', '500-2000'))
# Make a data table (i.e. a frequency count)
data <- table(data)
# Plot with `barplot`, making enough space for the labels
p <- barplot(data, ylim = c(0, max(data) + 1))
# Add the labels with some offset to be above the bar
text(x = p, y = data + 0.5, labels = names(data))

If it is the y values that you are after, you can change what you pass to the labels argument:

p <- barplot(data, ylim = c(0, max(data) + 1))
text(x = p, y = data + 0.5, labels = data)

Created on 2020-12-11 by the reprex package (v0.3.0)

stragu
  • 1,051
  • 9
  • 15