gpt4 book ai didi

r - 在 R 中使用 ggplot 填充行之间的区域

转载 作者:行者123 更新时间:2023-12-04 09:39:35 27 4
gpt4 key购买 nike

宗旨

我试图在 R 中用 ggplot 生成的图中填充两条线之间的区域。我想用与水平线下方不同的颜色填充水平线上方的线之间的所有内容。

我成功地用单一颜色填充了两条线之间的所有内容,但是,我没有设法通过两种不同的颜色区分垂直线的上方和下方。

代码

set.seed(123) 

# Load packages
library(tidyverse)

# Create sample dataframe
df <- data.frame(x=seq(1,50,1),y=runif(50, min = 0, max = 10))

# Generate plot
ggplot(data = df, aes(x = x, y = y)) +
geom_line() +
geom_hline(yintercept = 5) +
theme_classic() +
geom_ribbon(aes(ymin=5,ymax=y), fill="blue")

问题

如何用不同的颜色填充垂直线上方和下方的空间?

最佳答案

您可以计算两条线相交的点的坐标并将它们添加到您的数据框中:

m <- 5 # replace with desired y-intercept value for the horizontal line

# identify each run of points completely above (or below) the horizontal
# line as a new section
df.new <- df %>%
arrange(x) %>%
mutate(above.m = y >= m) %>%
mutate(changed = is.na(lag(above.m)) | lag(above.m) != above.m) %>%
mutate(section.id = cumsum(changed)) %>%
select(-above.m, -changed)

# calculate the x-coordinate of the midpoint between adjacent sections
# (the y-coordinate would be m), & add this to the data frame
df.new <- rbind(
df.new,
df.new %>%
group_by(section.id) %>%
filter(x %in% c(min(x), max(x))) %>%
ungroup() %>%
mutate(mid.x = ifelse(section.id == 1 |
section.id == lag(section.id),
NA,
x - (x - lag(x)) /
(y - lag(y)) * (y - m))) %>%
select(mid.x, y, section.id) %>%
rename(x = mid.x) %>%
mutate(y = m) %>%
na.omit())

使用此数据框,您可以定义两个单独的 geom_ribbon不同颜色的图层。下面的结果对比(注意:我还添加了一个 geom_point 图层来说明,并更改了颜色,因为原版中的蓝色有点刺眼……)
p1 <- ggplot(df,
aes(x = x, y = y)) +
geom_ribbon(aes(ymin=5, ymax=y), fill="dodgerblue") +
geom_line() +
geom_hline(yintercept = m) +
geom_point() +
theme_classic()

p2 <- ggplot(df.new, aes(x = x, y = y)) +
geom_ribbon(data = . %>% filter(y >= m),
aes(ymin = m, ymax = y),
fill="dodgerblue") +
geom_ribbon(data = . %>% filter(y <= m),
aes(ymin = y, ymax = m),
fill = "firebrick1") +
geom_line() +
geom_hline(yintercept = 5) +
geom_point() +
theme_classic()

result

关于r - 在 R 中使用 ggplot 填充行之间的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54687321/

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