1

I want a bar plot for the following data.

bloodgroup <- c("O",    "A",    "A",    "O",    "O",
                "B",    "B",    "A",    "A",    "A",
                "A",    "O",    "O",    "O",    "B",
                "O",    "O",    "A",    "O",    "A",
                "A",    "O",    "AB",   "B",    "O",
                "AB",   "B",    "O",    "A",    "AB")

I have written the following code, but it only returns the densities. I want the frequencies on the y-axis with on each bar at the top the number of frequencies. Any idea how to this?

 barplot(prop.table(table(bloodgroup)))
vahis100
  • 81
  • 1
  • 7
  • `barplot(table(bloodgroup))`? – Parfait Oct 16 '20 at 16:35
  • I worked, but how do I add the frequencies on top of each bar? – vahis100 Oct 16 '20 at 16:48
  • See [How to display the frequency at the top of each factor in a barplot in R](https://stackoverflow.com/q/12481430/1422451) and its dup reference, [add text to horizontal barplot in R, y-axis at different scale?](https://stackoverflow.com/q/4217207/1422451). Please [research](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) before you ask. – Parfait Oct 16 '20 at 16:51

1 Answers1

3

Try this approach using ggplot2 and dplyr pipelines. You need to transform your vector to dataframe and then summarise to obtain the counts. After that the plot can be sketched using geom_bar() and geom_text() to add the desired labels. Here the code:

library(ggplot2)
library(dplyr)
#Data
bloodgroup <- c("O",    "A",    "A",    "O",    "O",
                "B",    "B",    "A",    "A",    "A",
                "A",    "O",    "O",    "O",    "B",
                "O",    "O",    "A",    "O",    "A",
                "A",    "O",    "AB",   "B",    "O",
                "AB",   "B",    "O",    "A",    "AB")
#Code
bloodgroup %>% as.data.frame %>%
  rename(Var='.') %>%
  group_by(Var) %>% summarise(N=n()) %>%
  ggplot(aes(x=Var,y=N,fill=Var))+
  geom_bar(stat = 'identity',color='black')+
  scale_y_continuous(labels = scales::comma_format(accuracy = 2))+
  geom_text(aes(label=N),vjust=-0.25,fontface='bold')+
  theme_bw()+
  theme(axis.text = element_text(color='black',face='bold'),
        axis.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'),
        legend.title = element_text(color='black',face='bold'))

Output:

enter image description here

Or with base R:

#Code 2
xx <- barplot(table(bloodgroup),ylim=c(0, 14))
coords <- as.numeric(table(bloodgroup))
text(x = xx, y = coords, label = coords, cex = 0.8,pos = 3, col = "red")

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84