gpt4 book ai didi

r - 在 ggplot 中为美学之外的组添加 hline

转载 作者:行者123 更新时间:2023-12-05 01:26:48 25 4
gpt4 key购买 nike

我有一个折线图,其中包含不同年份和月份的指标。我想为每个月添加一条中线。

library(dplyr)
library(lubridate)
library(ggplot2)

set.seed(52)

data <- tibble(
date = seq.Date(from = as.Date("2017-01-01"), to = date("2020-12-31"), by = "month")
) %>%
mutate(
metric = rnorm(n(), mean = 5, sd = 2),
month = month(date, label = TRUE),
year = as.factor(year(date))
)

ggplot(data, aes(x = month, y = metric, color = year, group = year)) +
geom_line()

我尝试使用 geom_hline() 来执行此操作,但它只会为总中位数生成一条线。

ggplot(data, aes(x = month, y = metric, color = year, group = year)) +
geom_line() +
geom_hline(aes(yintercept = median(metric), group = month))

reprex package 创建于 2021-11-18 (v2.0.1)

为每个月创建中值线的最简单方法是什么?像这样: enter image description here

最佳答案

这是您正在寻找的...吗?

ggplot(data, aes(x = month, y = metric, color = year, group = year)) +
geom_line() +
geom_tile(data = function(df) df %>% group_by(month) %>%
summarise(metric = median(metric)),
aes(x = month, y = metric), height = 0.05, inherit.aes = FALSE)

enter image description here

或者,感谢@user20650 下面的评论,这也有效...

ggplot(data, aes(x = month, y = metric, color = year, group = year)) +
geom_line() +
stat_summary(aes(x = month, y = metric),
fun = median,
geom = "tile",
height = 0.05,
inherit.aes = FALSE)

关于r - 在 ggplot 中为美学之外的组添加 hline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70018442/

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