3
votes

I am a beginner in R. I am having problem in putting the count in my bar plot.

So my data look like this

> head(worker)
  stateur statemb state age tenure    joblost
1     4.5     167    42  49     21      other
2    10.5     251    55  26      2 slack_work
3     7.2     260    21  40     19      other
4      NA     245    56  51     17 slack_work
5     6.5     125    58  33      1 slack_work
6     7.5     188    11  51      3      other

I have plot the bar graph by using this code

table=table(worker$joblost)
barplot(table, main = "Vertical Bar Plot of the Job Lost")

But I want to put the frequency for each category of joblost on top of each bar. What can I do?

2

2 Answers

3
votes

Using text(). barplot() has an invisible output which you can capture with <- and use it for the x-positions of the text to add. For y= just add the table values plus something that looks good.

b <- barplot(tab, beside=TRUE, ylim=c(0, max(tab) + 15), 
             main="Vertical Bar Plot of the Job Lost", col=2:3, border=0)
text(b, tab + 5, tab, font=2, col=2:3)

enter image description here

Notice that by using "table" as name for your object, you attempt to overwrite the table() function! Always check beforehand if the name is free, typing ?table. If not, use something else.


Data:

tab <- structure(c(other = 56L, slack_work = 44L), .Dim = 2L, .Dimnames = structure(list(
    c("other", "slack_work")), .Names = ""), class = "table")
1
votes

You can use the following code for that

library(ggplot2)

  ggplot(worker,aes(x=factor(joblost)))+
  geom_bar(position="dodge")+ 
  labs(title="Vertical Bar Plot of the Job Lost", x="Job lost", y = "Frequency")+
  geom_text(aes(label=..count..),stat='count',position=position_dodge(0.9),vjust=-0.2)

enter image description here