1

I have 2 columns - one that has a number (Section) and the other one that says if its good or bad in r. Here is a sample data

df <- data.frame(G_or_B = c("Good", "Good", "Bad", "Good", "Good", "Bad", "Good", "Good"), Section = c(1,1,1,1, 2,2, 3,3) )

I need a ggplot (barplot) that says for every section, how many goods and how many bads it has in r and also displays the number of Goods and Bads in the bar. I'm new to r, but can understand pre-existing code good enough.

I have the code for ggplot that plots the bargraph but can't get it to display numbers. When I try the below code, I get the bar filled with "good" or "bad" instead of the count,

ggplot(df, aes(x = Section, fill = G_or_B) )+ 
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5))

The end result, ideally would have this ggplot, along with the number of Goods and Bads displayed on the bar

Plot after trying above code

Praneeth
  • 41
  • 1
  • 4

1 Answers1

1

The method you tried will work if you count your data first:

library(dplyr)
df_count = count(df, G_or_B, Section)
ggplot(df_count, aes(x = Section, y = n, fill = G_or_B) )+ 
  geom_col() +
  geom_text(aes(label = n), size = 3, position = position_stack(vjust = 0.5))

enter image description here

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294