gpt4 book ai didi

r - 在 R 中使用 ggplot 为两个不同组创建折线图

转载 作者:行者123 更新时间:2023-12-04 09:42:10 25 4
gpt4 key购买 nike

我正在尝试创建一个线图来描述两组/条件随时间的不同轨迹。我有两组在五个时间点(1、2、3、4、5)收集数据“吃”。我希望这些线能够连接每个组在五个时间点中的每一个的平均点,因此我在时间 1 处有两个点,在时间 2 处有两个点,依此类推。

这是一个可重现的示例:

#Example data
library(tidyverse)
library(ggplot2)
eat <- sample(1:7, size = 30, replace = TRUE)
df <- data.frame(id = rep(c(1, 2, 3, 4, 5, 6), each = 5),
Condition = rep(c(0, 1), each = 15),
time = c(1, 2, 3, 4, 5),
eat = eat
)
df$time <- as.factor(df$time)
df$Condition <- as.factor(df$Condition)

#Create the plot.
library(ggplot2)
ggplot(df, aes(x = time, y = eat, fill = Condition)) + geom_line() +
geom_point(size = 4, shape = 21) +
stat_summary(fun.y = mean, colour = "red", geom = "line")

问题是,我需要我的线水平移动(即显示两条不同颜色的线在 x 轴上移动)。但这段代码只是垂直连接点:

Here's what it looks like:

如果我不将 Time 转换为因子,而仅将 Condition 转换为因子,则会得到一团困惑的线条。我的实际数据中也发生了同样的情况。

example graph result

我希望它看起来像这样 like this从美学上讲,透明的错误信封包裹着每一行。但是,我不希望它是弯曲的,我希望线条是直的,连接每个点的平均值。

最佳答案

这是通过每次均值的直线段,范围设置为当时点的标准差。一个stat.summary 使用colour 美学创建平均线,另一个使用继承的fill 美学创建区域。 ggplot2::mean_se 是一个方便的函数,它接受一个向量并返回一个带有平均值和+/-一定数量的标准误差的数据帧。这是 stat_summaryfun.data 参数的正确格式,它将这些值传递给指定的 geom。此处,geom_ribbon 接受 yminymax 值以在图表中绘制一 strip 。

library(tidyverse)
set.seed(12345)
eat <- sample(1:7, size = 30, replace = T)
df <- data.frame(
Condition = rep(c(0, 1), each = 15),
time = c(1, 2, 3, 4, 5),
eat = eat
)
df$Condition <- as.factor(df$Condition)

ggplot(df, aes(x = time, y = eat, fill = Condition)) +
geom_point(size = 4, shape = 21, colour = "black") +
stat_summary(geom = "ribbon", fun.data = mean_se, alpha = 0.2) +
stat_summary(
mapping = aes(colour = Condition),
geom = "line",
fun.y = mean,
show.legend = FALSE
)

reprex package 创建于 2018-07-09 (v0.2.0)。

关于r - 在 R 中使用 ggplot 为两个不同组创建折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51253479/

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