gpt4 book ai didi

r - 如何在 R 中用不同颜色填充 geom_ribbon?

转载 作者:行者123 更新时间:2023-12-05 01:49:00 28 4
gpt4 key购买 nike

我正在尝试根据 x 值对 geom_ribbon 使用不同的填充(对于 Temp = 0-20 一个填充,20-30.1 另一个填充和 > 30.1 另一个填充)。我正在使用以下代码

library(tidyverse)

bounds2 <- df %>%
mutate(ymax = pmax(Growth.rate, slope),
ymin = pmin(Growth.rate, slope),
x_bins = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5)))

ggplot(df, aes(x = Temp, y = Growth.rate)) +
geom_line(colour = "blue") +
geom_line(aes(y = slope), colour = "red") +
scale_y_continuous(sec.axis = sec_axis(~ .^1, name = "slope")) +
geom_ribbon(data = bounds2, aes(Temp, ymin = ymin, ymax = ymax, fill = x_bins),
alpha = 0.4)

它在输出后返回我 enter image description here

正如您从输出中看到的,一些区域仍然是空的。现在如何填充曲线中的那些部分?这是数据

df = structure(list(Temp = c(10, 13, 17, 20, 25, 28, 30, 32, 35, 38
), Growth.rate = c(0, 0.02, 0.19, 0.39, 0.79, 0.96, 1, 0.95,
0.65, 0), slope = c(0, 0.02, 0.16, 0.2, 0.39, 0.1, 0.03, -0.04,
-0.29, -0.65)), row.names = c(NA, 10L), class = "data.frame")

最佳答案

这是一个涉及在区域之间的边界处插入新点的解决方案。我使用 approxTemp=30.1 处获取 yminymax 的值,并将其添加到绘图数据集中.

然后,我没有像您那样只使用一次 cut,而是使用了两次,一次在每个集合中包含下限,然后一次包含上限。然后我对数据进行长整形,并删除不需要的行的重复数据。

如果放大足够大,您可以看到边界在 30.1 而不是 30。

bounds2 <- df %>% 
mutate(ymax = pmax(Growth.rate, slope),
ymin = pmin(Growth.rate, slope))
bounds2 <- bounds2 |>
add_case(Temp=30.1,
ymax=approx(bounds2$Temp,bounds2$ymax,xout = 30.1)$y,
ymin=approx(bounds2$Temp,bounds2$ymin,xout = 30.1)$y) |>
mutate(x_bins2 = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5),right=FALSE, labels=c("0-20","20-30.1","30.1-max")),
x_bins = cut(Temp, breaks = c(0,20,30.1,max(Temp)+5), labels=c("0-20","20-30.1","30.1-max"))) |>
tidyr::pivot_longer(cols=c(x_bins2, x_bins), names_to = NULL, values_to = "xb") |>
distinct()

ggplot(df, aes(x = Temp, y = Growth.rate)) +
geom_line(colour = "blue") +
geom_line(aes(y = slope), colour = "red") +
scale_y_continuous(sec.axis = sec_axis(~ .^1, name = "slope")) +
geom_ribbon(data = bounds2, aes(Temp, ymin = ymin, ymax = ymax, fill = xb),
alpha = 0.4)

enter image description here

关于r - 如何在 R 中用不同颜色填充 geom_ribbon?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74560448/

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