Hugh Warden
Hugh Warden

Reputation: 446

Show subsets of data in ggplot2 sequentially without changing formatting?

I have produced this graph in ggplot2

Example graph

Here is the code I used to produce it

library(ggplot2)
library(reshape)

l_mat <- matrix(0, ncol = 4, nrow = 4)
l_mat[1,1:2] <- c(1,-1)
l_mat[2,1:3] <- c(-1,2,-1)
l_mat[3,2:4] <- c(-1,2,-1)
l_mat[4,3:4] <- c(-1,1)

ev <- eigen(l_mat)$vectors
ev <- matrix(as.numeric(ev), 4, 4)
ev <- apply(ev, 2, function(x) {x/sum(abs(x))})
ev <- data.frame(ev)
names(ev) <- c("Eigenvector 4","Eigenvector 3","Eigenvector 2","Eigenvector 1")

p.data <- melt(ev)
names(p.data) <- c("Eigenvector", "Value")
p.data$Vertex <- rep(1:4, 4)
ggplot(p.data, aes(Vertex, Value, colour = Eigenvector)) + geom_line(linetype = "dashed") + geom_point()

I would like to use this figure in a presentation but I would like to have each set of data for each eigenvector appear sequentially. By this I mean I would like to have a picture that only has the line and points for Eigenvector 1, then for Eigenvector 1 and 2, then for 1 and 2 and 3 and then finally all of them. But I would like the formatting of the rest of the graph to stay the same (colours, plot area, legend etc) to stay the same so that when I put it into LaTeX it looks like each line is appearing.

Thank you in advance

Upvotes: 0

Views: 47

Answers (1)

tamtam
tamtam

Reputation: 3671

To create a plot-flipbook you can loop through your Eigenvectors like this:

library(tidyverse)

for(i in 1:4){
  p <- p.data %>% 
    filter(Eigenvector %in% paste("Eigenvector", 1:i)) %>% 
    ggplot(aes(Vertex, Value, colour = Eigenvector)) +
    geom_line(linetype = "dashed") +
    geom_point() +
    scale_y_continuous(limits = c((min(p.data$Value)), max(p.data$Value))) +
    scale_color_discrete(drop = FALSE)
  
  assign(paste0("plot_Eigenvecor_", i), p)
  plot(p)
}

scale_y_continuous fixes your y-axis to the min and max values of the whole dataset. While scale_color_discrete(drop = FALSE) forces to use every factor level in the legend even when not needed.

Data

structure(list(Eigenvector = structure(c(1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("Eigenvector 4", 
"Eigenvector 3", "Eigenvector 2", "Eigenvector 1"), class = "factor"), 
    Value = c(0.146446609406727, -0.353553390593274, 0.353553390593273, 
    -0.146446609406726, -0.25, 0.25, 0.25, -0.25, -0.353553390593274, 
    -0.146446609406726, 0.146446609406726, 0.353553390593273, 
    0.25, 0.25, 0.25, 0.25), Vertex = c(1L, 2L, 3L, 4L, 1L, 2L, 
    3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L)), row.names = c(NA, 
-16L), class = "data.frame")

Upvotes: 1

Related Questions