简体   繁体   中英

Need help plotting a ggplot

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 good s and how many bad s 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

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))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM