You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用R在同图绘制逐时降水量与按日累计降水量

调整方案

你之前的代码使用timestamp字段分组,但从示例数据可以看到所有行的timestamp值完全一致,所以会对全量数据做全局累计,无法实现按日重置的效果,调整逻辑如下:

  • 从datetime字段提取自然日期作为分组依据,可直接用lubridate包的date()函数提取
  • 将累计计算的分组字段从timestamp替换为提取的自然日期字段,inca的累计降水量也需要同步调整分组逻辑

修改后完整代码

# 未安装对应包可先执行 install.packages(c("lubridate","dplyr","ggplot2"))
library(lubridate)
library(dplyr)
library(ggplot2)

df <- df  %>% 
  mutate(date = date(datetime)) %>% # 提取datetime对应的自然日期
  group_by(date) %>% # 按自然日分组,替换原有group_by(timestamp)逻辑
  mutate(
    aws_pcp_cumulative = cumsum(aws.pr_sum),
    inca_pcp_cumulative = cumsum(inca.RR.max) # 补充inca的日累计计算
  ) 

c3 <- c("inca" = "#6aa6fa", "AWS" = "#2ECBE9")

# 绘图部分保持原有逻辑即可
p3 = ggplot(df, aes(x=datetime)) +
geom_bar(stat = "identity", aes(x = datetime + shift/2, y = aws.pr_sum, color="AWS"), size=0.7, fill=NA, width=wd ) +
geom_line(data = df, aes(x = datetime, y = aws_pcp_cumulative, color =  "AWS"), size=1.2,alpha=0.2) +
geom_bar(stat = "identity", aes(x = datetime - shift/2, y = inca.RR.max, color="inca"), size=0.7, fill=NA, width=wd) +
geom_line(data = df, aes(x = datetime, y = inca_pcp_cumulative, color = "inca"), size=1.2,alpha=0.2) +
geom_text(aes(label=laws, x = datetime, y = aws.pr_sum, color="AWS"), vjust = -0.5, size=3) +
geom_text(aes(label=linca, x = datetime, y = inca.RR.max, color="inca"), vjust = -0.5, size=3) +
scale_x_datetime(breaks=brks, labels = lbls, date_labels="%d.%m %H:%M") +
  labs(x="",
       y= "",
       color="zrážky [mm/h]") +
  scale_color_manual(values = c3) +
  theme(
    panel.grid.major.x = element_blank(),
    legend.position = c(0.01,0.95),
    legend.justification = c("left", "top"),
    legend.box.just = "left",
    legend.margin = margin(6, 30, 6,6),
    legend.title = element_text(size = 12))  

内容的提问来源于stack exchange,提问作者meteorolog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:45:08