[英]can't sum in ggplot for R shiny
I am working on a R shiny app and I am struggling with ggplot.我正在开发一个 R shiny 应用程序,我正在与 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.在应用程序中,用户可以选择按年龄过滤或在 ggplot 中显示所有年龄。
However, ggplot isn't summing Students' values.但是,ggplot 并未总结学生的价值观。 I don't understand why.
我不明白为什么。 How can I tell ggplot to sum values?
我如何告诉 ggplot 对值求和?
Here's my ggplot code:这是我的ggplot代码:
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.先感谢您。
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()
:虽然您可以在
geom_bar
和geom_text
中使用stat_summary
或stat="summary"
来计算总和,但恕我直言,更简单的选择是在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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.