I am working on a R shiny app and I am struggling with ggplot. Here's my dataset :
Year = c(2021, 2022,2023,2021,2023,2020,2021,2023,2022,2023,2022,2021,2020,2020,2023)
Country = c("France", "France", "Italy", "England", "Italy", "England", "Germany", "Germany", "Germany", "France", "France", "Italy", "England", "Italy", "England")
Age = c(22,23,20,24,21,25,21,21,23,24,25,21,20,20,25)
Students = c(1,5,100,43,76,23,43,50,122,5,67,32,53,22,90)
Gender = c("Boy","Girl","Boy","Girl","Boy","Boy","Girl","Girl","Boy","Boy","Girl","Girl","Boy","Girl","Boy")
df = data.frame(Year, Country, Age, Students, Gender)
In the app, the user can choose to filter by age or to display all ages in a ggplot.
However, ggplot isn't summing Students' values. I don't understand why. How can I tell ggplot to sum values ?
Here's my ggplot code :
g <- ggplot(df,
aes(x=Year,
y=Students,
fill=Gender))
geom_bar(stat='identity', position='dodge')
geom_text(aes(label = Students))
facet_wrap(~ Country)
xlab("")
g <- ggplotly(g)
g
Thank you in advance.
CodePudding user response:
While you could use stat_summary
or stat="summary"
both in geom_bar
and geom_text
to compute the sum, IMHO the easier option would be to summarise your data outside of ggplot()
:
library(ggplot2)
library(plotly)
df <- df |>
group_by(Country, Year, Gender) |>
summarise(Students = sum(Students), .groups = "drop")
g <- ggplot(
df,
aes(
x = Year,
y = Students,
fill = Gender
)
)
geom_col(position = "dodge")
geom_text(aes(label = Students))
facet_wrap(~Country)
xlab("")
ggplotly(g)