我在R中做了很少有趣的绘图,所以我正在寻找一些帮助。提前谢谢。
我有两个data.frames:
> dim(MyDates)
[1] 371 1
> dim(SumData)
[1] 371 30
MyDates持有371周一至周五的日期。 SumData保存30个不同的数据流,与MyDates正确对齐。
数据分为6组,如下所示:
groups=list(1:5,6:10,11:15,16:20,21:25,26:30)
我想创建一个绘图,SumData中的所有30列绘制为(我认为)实线。 X轴必须按升序排列为MyDates。我想以不同的方式为每个组着色。
group1 = red
group2 = yellow
group3 = green
group4 = cyan
group5 = blue
group6 = magenta
1个图,30行,6组,5行/组,每组预定义颜色。
我该如何做到这一点?
谢谢!
答案 0 :(得分:1)
有点黑客,但这可以完成工作......
require(zoo)
# z <- zoo(SumData, MyDates)
z <- zoo(matrix(rnorm(30*371),371,30),Sys.Date()-371:1)
Groups <- list(1:5,6:10,11:15,16:20,21:25,26:30)
Colors <- c("red","yellow","green","cyan","blue","magenta")
Col <- vector("character",length(unlist(Groups)))
for(i in 1:length(Groups)) {
Col[Groups[[i]]] <- Colors[i]
}
plot(z, screens=1, col=Col)
答案 1 :(得分:0)
这是一个正确颜色的ggplot答案。
require(ggplot2)
ngroups = 6
dummygroup <- function(g)
(g * 50) + apply(matrix(rnorm(371 * 5), ncol = 5), 2, cumsum)
SumData <- do.call("data.frame", lapply(ngroups:1, dummygroup))
MyDates <- as.Date(1:371, origin="2009-01-01")
df <- data.frame(MyDates, SumData)
dfmelt <- melt(df, id = "MyDates", variable_name = "series")
dfmelt$Groups <- factor(rep(1:ngroups, each = 371 * 5))
Colors <- c("red","yellow","green","cyan","blue","magenta")
p <- ggplot(dfmelt, aes(MyDates, value, color = Groups, group = series))
p <- p + geom_line() + scale_colour_manual(values = Colors)
print (p)