gpt4 book ai didi

r - 如何使用 stat_summary 和 geom = "line"在 ggplot2 中绘制 NA 间隙?

转载 作者:行者123 更新时间:2023-12-04 20:27:06 25 4
gpt4 key购买 nike

如何在 stat_summary 中将包含 NA 的数据绘制为“间隙”与 geom = "line" ?
geom_line()是可行的通过使用 geom_path()反而
(参见 how to plot NA gaps using ggplot2How to plot data containing NA's as "gaps" in geom_line )。

MWE 基于@stuttungr 的示例(来自 here)

    df = data.frame( x = c(1:10), y = c(1:10) )
df[5:7, ]=NA

# get NO gap as expected
ggplot(data=df, aes(x,y)) +
geom_point(color = "green", size = 5) +
geom_line()

geom_line
    # get the gap as expected
ggplot(data=df, aes(x,y)) +
geom_point(color = "green", size = 5) +
geom_path()

geom_path
    # get NO gap unfortunately
ggplot(data=df, aes(x,y)) +
geom_point(color = "orange", size = 5) +
stat_summary(fun.y = mean, geom = "line")

stat_summary_with_line

非常感谢您的帮助!

最佳答案

您可以为 group 添加一列

ggplot(data = transform(df, group = with(rle(is.na(df$x)), rep(seq_along(values), lengths))),
aes(x, y, group = group)) +
geom_point(color = "orange", size = 5) +
stat_summary(fun.y = mean, geom = "line")

enter image description here

这是 data
transform(df, group = with(rle(is.na(df$x)), rep(seq_along(values), lengths)))
# x y group
#1 1 1 1
#2 2 2 1
#3 3 3 1
#4 4 4 1
#5 NA NA 2
#6 NA NA 2
#7 NA NA 2
#8 8 8 3
#9 9 9 3
#10 10 10 3

关于r - 如何使用 stat_summary 和 geom = "line"在 ggplot2 中绘制 NA 间隙?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57808684/

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