Dear R users,
# I need to iterate a conditional mapping (e.g. aes(colour>1.5)) with ggplot2.
# I'll describe my case below.
# Let say I have a longitudinal data set with i=22 individuals; j=10 time period; 2 outcome measures (ma and mb);
# a factor variable with two values (Code) and thresholds for the outcome measures (e.g., 4.5 and 5).
df <- data.frame(id = sort(rep(1:22, 10)),
time = rep(1:10, 22),
ma = rep(round(rnorm(1:10, mean = 5), 22), 2),
mb = rep(round(rnorm(1:10, mean = 5), 22), 2),
Code = rep(c(1, 2), 110)
)
# The below procedure produce the desired plot.
library(ggplot2)
# plot 1
ggplot(data = df, aes(x = time, y = m.a, colour = m.a > 5)) +
geom_point() +
facet_wrap(~Code) +
scale_colour_manual(name = 'FVC > 4.77', values = setNames(c('red','green'),c(T, F))) +
xlab("Measurement Day")
# Nevertheless when I am going to iterate I can not find the adequate place
# of the conditional value, colour = m.a >5. An example bellow:
# plot 2
nV <- names(df[3:4])
indx <- c(5, 4.5)
library(ggplot2)
for(i in 1:length(nV)){
nam <- paste("plot", nV, sep = "_")
assign(nam[i], ggplot(data = spiro, aes(x = time)) +
geom_point(aes_string(y = nV[i], colour = nV[i] > indx[i])) +
scale_colour_manual(name = paste(nV[i], ">", indx[i], sep = " "),
values = setNames(c('red','green'), c(T, F))) +
xlab("Measurement Day")
)
}
plot_ma
plot_mb
# I understand that the > indx[i] can not go within the aes_string() but I can not find
# the adequate place or function to make this work.
# When I treat > indx[i] as continuous variable I can produced more or less the result I want,
# as the following plot 3:
# plot 3
# Rangees
uprg <- apply(df[, c("ma", "mb")], 2,
function(x) range(x, na.rm = TRUE))[2,] # substract the 20%
lorg <- apply(df[, c("ma", "mb")], 2,
function(x) range(x, na.rm = TRUE))[1,]
for(i in 1:length(nV)){
nam <- paste("plot", nV, sep = "_")
assign(nam[i], ggplot(data = df, aes(x = time)) +
geom_point(aes_string(y = nV[i], colour = nV[i])) +
scale_colour_continuous(limits = c(lorg[i], uprg[i]), low = "green", high = "red") +
xlab("Measurement Day") +
facet_wrap(~Code)
)
}
plot_ma
plot_mb
# Nevertheless, I want only two colors. One above (red) and one bellow (green) the threshold.
# Any guidance is appreciated.
Thanks,
Jose Bartolomei