Reputation: 155
I have a data set of time-series trajectories. Additionally, each time series carries with it a statistical weighting factor: for example time series #4 might have a weight of 0.023 whereas time series #25 might have a weight of 0.321.
I have a lot of these time series, and I'd like to plot all of them on the same plot (in the same color), and have their opacity be proportional to their weight, in order to visualize a weighted distribution in space and time.
I've gotten nearly all the way there using ggplot2, but have spent a few days struggling to use the alpha aes to do the job properly and have had no luck. I'm trying to feed the alpha aes a vector of weights, but it doesn't seem to work. Unfortunately none of the other answers here use a source for the alpha values that is external to the data frame.
Is this a syntax problem, or am I thinking about this wrong? The alpha aes seems designed to use something internal to the data frame as input, but I couldn't figure out how to integrate the weights to the data frame without bloating my data to an unmanageable size.
Everything in the following code works except the last line:
# parameters for test data
N_timepoints <- 25
N_series <- 1000
# generate N_timepoints*N_series matrix of data
test_data <- matrix(rnorm(N_timepoints*N_series,mean=0,sd=0.1), N_timepoints, N_series)
test_data <- apply(test_data, 2, cumsum)
test_data <- as.data.frame(test_data)
# generate N_series length vector of weights
test_weights <- rexp(N_series, rate=1)
test_weights <- test_weights/sum(test_weights)
test_weights <- as.data.frame(test_weights)
# add a column to the data frame to label each timepoint
test_timepoints <- seq(N_timepoints)
test_data_and_timepoints <- cbind(test_timepoints, test_data)
test_data_and_timepoints_long <- melt(test_data_and_timepoints, id="test_timepoints")
# construct basic plot
p_test <- ggplot(data=test_data_and_timepoints_long, aes(x= test_timepoints, y=value, group=variable))
# tweak background and labels
p_test <- p_test +
theme_bw() +
theme(legend.position="none") +
ylab("Coordinate") +
xlab("Time Point")
# plot with constant alpha -- not what I want, but close
p_test_alpha <- p_test + geom_line(aes(alpha = 1)) + scale_alpha(range = c(0.01, 0.1))
# plot with alpha proportional to weight -- what I actually want, but doesn't work
p_test_var_alpha <- p_test + geom_line(aes(alpha = test_weights))
Upvotes: 2
Views: 561
Reputation: 52637
Your test_weights
variable needs to be a vector of the same size as your data.frame. Here is a solution:
p_test_var_alpha <-
p_test +
geom_line(aes(alpha = rep(unlist(test_weights), each=25)))
Although you have to be careful to make sure the vector is ordered properly. It would be better to introduce it into the data.frame directly.
Beautiful graph, btw (and I'm not patting myself on the back, I just got it to print, you designed it).
Upvotes: 2