gpt4 book ai didi

r - 在 ggplot2 中对 y 轴求和

转载 作者:行者123 更新时间:2023-12-03 16:58:37 25 4
gpt4 key购买 nike

我有一个简单的 data.frame:

exdataframe <- data.frame(
date = c("2020-10-18","2020-10-20","2020-10-21","2020-10-31","2020-10-29","2020-11-01","2020-11-02"),
Salesman = c("Bob","Mark","Rob","Rob", "Mark","Richard","Richard"),
values = c(10,50,30,100,120,90,20)
)
exdataframe$date <- as.Date(exdataframe$date) # transform to Date class

所以我绘制:
ggplot(exdataframe, aes(x = cut(date, breaks = "month"), y = values, fill=Salesman)) + 
geom_bar(stat = "identity",position=position_dodge()) +
geom_text(aes(label=values), position=position_dodge(width=0.9), vjust=-0.25) +
xlab("Month")

enter image description here
我的问题是如何按销售员列和按月和销售员分组对所有 Y 轴值求和?

最佳答案

我们可以通过sum做一个群

library(dplyr)
library(lubridate)
library(ggplot2)
library(zoo)
exdataframe %>%
group_by(month = as.yearmon(date), Salesman) %>%
summarise(values = sum(values), .groups = 'drop') %>%
ggplot(aes(x = month, y = values, fill = Salesman, group = Salesman)) +
geom_bar(stat = 'identity', position = position_dodge())
-输出
enter image description here

关于r - 在 ggplot2 中对 y 轴求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64635700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com