R ggplot2使用时间序列和多样条曲线绘制直线
这个问题的主题很简单,但让我发疯: 1.如何使用R ggplot2使用时间序列和多样条曲线绘制直线,r,ggplot2,lines,spline,melt,R,Ggplot2,Lines,Spline,Melt,这个问题的主题很简单,但让我发疯: 1.如何使用melt() 2.如何处理单个图像中的多行 这是我的原始数据: a 4.17125 41.33875 29.674375 8.551875 5.5 b 4.101875 29.49875 50.191875 13.780625 4.90375 c 3.1575 29.621875 78.411875 25.174375 7.8012 问题1: 我从这篇文章学到了如何绘制多变量的多条线,
melt()
2.如何处理单个图像中的多行
这是我的原始数据:
a 4.17125 41.33875 29.674375 8.551875 5.5
b 4.101875 29.49875 50.191875 13.780625 4.90375
c 3.1575 29.621875 78.411875 25.174375 7.8012
问题1:
我从这篇文章学到了如何绘制多变量的多条线,就像这样:
以下代码可以得到上面的图。然而,x轴确实是时间序列
df <- read.delim("~/Desktop/df.b", header=F)
colnames(df)<-c("sample",0,15,30,60,120)
df2<-melt(df,id="sample")
ggplot(data = df2, aes(x=variable, y= value, group = sample, colour=sample)) + geom_line() + geom_point()
df您的变量
列是一个因子(您可以通过调用str(df2)
进行验证)。只需将其转换回数值:
df2$variable <- as.numeric(as.character(df2$variable))
这给了我类似的东西:
p <- ggplot(data = df2, aes(x=variable, y= value, group = sample, colour=sample)) +
geom_line() +
geom_point()
library(splines)
p + geom_smooth(aes(group = sample),method = "lm",formula = y~bs(x),se = FALSE)
您的变量列是一个因素(您可以通过调用str(df2)
进行验证)。只需将其转换回数值:
df2$variable <- as.numeric(as.character(df2$variable))
这给了我类似的东西:
p <- ggplot(data = df2, aes(x=variable, y= value, group = sample, colour=sample)) +
geom_line() +
geom_point()
library(splines)
p + geom_smooth(aes(group = sample),method = "lm",formula = y~bs(x),se = FALSE)
非常感谢您的帮助!在我的例子中,我尝试了as.numeric(df2$Time)
将它们转换成数字,但它返回我1234512345125
,这真的让我发疯。再次感谢。@Puriney请注意,我在回答中并不是这样做转换的。因子看起来像字符向量,但它们不是!它们是整数代码和一组与代码配套的标签。因此,as.numeric
将只返回整数代码。这就是为什么我先转换成角色。一种更神秘的方法是as.numeric(levels(df2$Time)[df2$Time])
。非常感谢您的帮助!在我的例子中,我尝试了as.numeric(df2$Time)
将它们转换成数字,但它返回我1234512345125
,这真的让我发疯。再次感谢。@Puriney请注意,我在回答中并不是这样做转换的。因子看起来像字符向量,但它们不是!它们是整数代码和一组与代码配套的标签。因此,as.numeric
将只返回整数代码。这就是为什么我先转换成角色。一种更神秘的方法是as.numeric(levels(df2$Time)[df2$Time])
。