【发布时间】:2016-12-16 20:26:52
【问题描述】:
随着时间的推移,我需要为研究中的各个受试者绘制大量药物浓度图,并且我想根据他们服用的药物始终如一地设置颜色。不过,并非所有患者都服用相同的药物。这是我尝试过的:
library(plyr)
library(ggplot2)
library(gridExtra)
A <- data.frame(Time = seq(0, 20, 5),
DrugConcentration = 100*exp(-0.25*seq(0, 20, 5)),
Drug = "Midazolam")
B <- data.frame(Time = rep(seq(0, 20, 5), 2),
DrugConcentration = c(100*exp(-0.25*seq(0, 20, 5)),
75*exp(-0.1*seq(0, 20, 5))),
Drug = rep(c("Midazolam", "Dextromethorphan"), each = 5))
C <- data.frame(Time = rep(seq(0, 20, 5), 3),
DrugConcentration = c(100*exp(-0.25*seq(0, 20, 5)),
75*exp(-0.1*seq(0, 20, 5)),
50*exp(-0.15*seq(0, 20, 5))),
Drug = rep(c("Midazolam", "Dextromethorphan", "Tolbutamide"),
each = 5))
D <- data.frame(Time = rep(seq(0, 20, 5), 2),
DrugConcentration = c(100*exp(-0.25*seq(0, 20, 5)),
50*exp(-0.15*seq(0, 20, 5))),
Drug = rep(c("Midazolam", "Tolbutamide"),
each = 5))
DrugList <- list(A, B, C, D)
MyColors <- data.frame(Drug = c("Midazolam", "Dextromethorphan", "Tolbutamide"),
Color = c("red", "green", "blue"),
stringsAsFactors = FALSE)
PlotList <- list()
for(i in 1:length(DrugList)){
DrugList[[i]] <- arrange(DrugList[[i]], Drug, Time)
MyColors.temp <- join(DrugList[[i]][, c("Drug", "Time")],
MyColors, by = "Drug")
MyColors.temp <- unique(MyColors.temp[, c("Drug", "Color")])
MyColors.temp <- arrange(MyColors.temp, Drug)
PlotList[[i]] <-
ggplot(DrugList[[i]],
aes(x = Time, y = DrugConcentration,
color = Drug)) +
geom_point() + geom_line() +
scale_color_manual(values = MyColors.temp$Color)
}
循环运行,但是当我尝试时
marrangeGrob(PlotList, nrow = 2, ncol = 2)
我得到错误:Insufficient values in manual scale. 3 needed but only 2 provided. 如果我单独查看每个图,例如,通过键入 PlotList[[1]],前两个图至少会生成图(尽管每种药物的颜色不一致,而不是我指定),但第三个是给我关于没有足够值的错误的那个。
这里发生了什么?为什么这不起作用?
【问题讨论】: