gpt4 book ai didi

r - 使用 ggplot2 构建折线图

转载 作者:行者123 更新时间:2023-12-01 22:10:39 29 4
gpt4 key购买 nike

我需要绘制三条线(在一张图表上),每条线代表一个实验室团队的数据(每个团队两个变量)。理想情况下,图表应该看起来美观(因此使用 ggplot2!),但形式与下面所示的折线图类似。我不明白如何使用 gggplot2 库将多条线绘制到单个图表上。我目前对 ggplot2 库的了解/技能还很低,但我在下面列出了我的初步努力。

http://www.harding.edu/fmccown/r/#linecharts

编辑:每行由两个向量构成,如下所示:

temp = c(4, 25, 50, 85, 100) 
enzyme_activity = c(0.543, 0.788, 0.990, 0.898, 0.882)

x 轴上有温度变量,每条线都有不同的颜色,以便可以区分它们。

编辑2:

amyA = c(0.091, 0.147, 0.202, 0.236, 0.074)
temp = c(4, 23, 37, 65, 100)
df = data.frame(temp, amyA)

ggplot(df, aes(x = temp, y = amyA, col = 'blue')) + geom_line()

第二次编辑中的代码不会生成蓝线,并且图例完全错误。如果我使用不同的数据重复两次 ggplot 调用,则只会绘制一条线。

最佳答案

关键是在绘图之前组织数据,以便在数据框中有一个 factor 列,指示每组 x 的单独行,y 值。例如:

set.seed(1)
df1 <- data.frame(e1 = sort(runif(5, 0.05, 0.25)),
e2 = sort(runif(5, 0.05, 0.25)),
e3 = sort(runif(5, 0.05, 0.25)),
t1 = sort(runif(5, 1, 100)),
t2 = sort(runif(5, 1, 100)),
t3 = sort(runif(5, 1, 100))
)
### reshape this to give a column indicating group
df2 <- with(df1,
as.data.frame(cbind( c(t1, t2, t3),
c(e1, e2, e3),
rep(seq(3), each=5) )
))
colnames(df2) <- c("temp","activity","team")
df2$team <- as.factor(df2$team)

然后

library(ggplot2)
ggplot(df2, aes(x=temp, y=activity, col=team)) + geom_line()

给予:enter image description here

关于r - 使用 ggplot2 构建折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19011959/

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