我可以根据日期列和第二列值在R中创建一个黄土线。加载数据集后,我可视化下面的一列数据:
scatter.smooth(x=1:length(goals$Value), y=goals$Value)
但是,如何为其他列添加多个黄土线?在一个图形中绘制所有黄土线的代码是什么?比如说,每个附加列都命名为Value2,Value3,Value4等。
答案 0 :(得分:2)
如果你还没有考虑过它,那么包ggplot2
会使这些图形问题更容易处理,并提供更好的图表:
library(ggplot2)
library(tidyr)
set.seed(123)
df <- data.frame("days"=1:25, "v1"=rnorm(25), "v2"=(rnorm(25)+0.1))
#Reshape data from wide to long
df2 <- gather(df,var,val,c(v1,v2))
ggplot(df2,aes(x = days, y = val)) +
geom_point() +
geom_smooth(aes(colour = var),se = F)
如果您不想重塑数据,可以添加如下所示的单独行:
ggplot(df,aes(x = days, y = v1)) +
geom_point() + #Add scatter plot
geom_smooth(aes(colour = 'v1'),se = F) + #Add loess 1
geom_smooth(aes(y = v2,colour = 'v2'),se = F) + #Add loess 2... and so on
scale_colour_discrete(name = 'Line',
breaks = c('v1','v2'),
labels = c('variable 1','variable 2')) #Define legend
答案 1 :(得分:1)
您将使用lines
功能:
# create test data
set.seed(123)
df <- data.frame("days"=1:25, "v1"=rnorm(25), "v2"=(rnorm(25)+0.1))
# first plot
scatter.smooth(x=df$days, y=df$v1)
# add plot of second lowess line
lines(loess.smooth(x=df$days, y=df$v2))
为线条添加颜色:
scatter.smooth(x=df$days, y=df$v1, lpars=list(col="red"))
lines(loess.smooth(x=df$days, y=df$v2), col="green")