Shakil Ahmed Shaon
Shakil Ahmed Shaon

Reputation: 119

Clustered Bar Plot Using ggplot2

Snapshot of my data frame

Basically I want to display a barplot which is grouped by Methods i.e I want to display the number of people conducted the tests, the number of positive test results had found for each of the methods. Also, I want to display all the numbers and percentages as labels on the bar. I am trying to display these using ggplot2. But I am failing every time.

Any helps.

Thanks in advance

Upvotes: 0

Views: 301

Answers (1)

dc37
dc37

Reputation: 16178

I'm not sure to have fully understand your question. But I will suggest you to take look on geom_text.

library(ggplot2)

ggplot(df, aes(x = methods, y = percentage)) + 
  geom_bar(stat = "identity") + 
  geom_text(aes(label = paste0(round(percentage,2), " (",positive," / ", people,")")), vjust = -0.3, size = 3.5)+
  scale_x_discrete(limits = c("NS1", "NS1+IgM", "NS1+IgG","Tourniquet")) + 
  ylim(0,100)

enter image description here

Data:

df = data.frame(methods = c("NS1", "NS1+IgM","NS1+IgG","Tourniquet"),
                people = c(542,542,541,250),
                positive = c(505,503,38,93))
df$percentage = df$positive / df$people * 100

> df
     methods people positive percentage
1        NS1    542      505   93.17343
2    NS1+IgM    542      503   92.80443
3    NS1+IgG    541       38    7.02403
4 Tourniquet    250       93   37.20000

Does it answer your question ? If not, can you clarify your question by adding the code you have tried so far in ggplot ?

Upvotes: 3

Related Questions