Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding COUNT in barplot in R

Tags:

r

bar-chart

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?

like image 960
Izzah Avatar asked May 24 '26 22:05

Izzah


2 Answers

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")
like image 163
jay.sf Avatar answered May 26 '26 14:05

jay.sf


The following code works for graphics created with ggplot2 package (not base R, as the OP):

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

like image 34
Bappa Das Avatar answered May 26 '26 14:05

Bappa Das



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!