R/figures.R

Defines functions plot_eeg plot_fft

Documented in plot_eeg plot_fft

#' Plot a raw EEG session
#' Args
#' eeg Numeric vector of voltage values (or matrix, that will be deconstructed row-wise)
#' srate Sampling rate (samples/sec)
#' limits Optional limits used for plotting (defaults to whole record)
#' marks Optional X values where dashed lines will be drawn (default no none)
plot_eeg <- function(eeg, srate, limits=c(0, length(eeg) / srate), marks=NULL) {
  y <- as.vector(eeg)
  t <- seq(0, length(eeg) / srate, length.out = length(y))  
  ylim = c(min(y) * 1.1, max(y) * 1.1)

  p <- ggplot() + theme_minimal() + 
    geom_line(aes(t, y), size=.2) +
    scale_x_continuous(name="Time (s)", limits=limits) +
    scale_y_continuous(name="Amplitude (uV)", limits=ylim)

  if(!is.null(marks)) p <- p + geom_rug(aes(x=marks)) #geom_vline(aes(xintercept=marks), linetype=2)

  p
}

#' Plot EEG in frequency domain
#' time Total time (in seconds) of the segment in EEG
#' fmax Maximum frequency to display (in Hz)
#' marks Frequencies (in Hertz) to mark
plot_fft <- function(eeg, time, limits=c(0,20), fmax = 50, marks=NULL) {
  y <- as.vector(eeg)
  fres <- 1 / time      # Fraction in Hz of sample distance
  fx = seq(0, fres*(length(eeg)/2), fres)
  max_idx <- as.integer(fmax/fres)
  fx = fx[1:max_idx]
  fvals = abs(fft(y))[1:max_idx]

  fr_df <- tibble(fx=fx, fvals=fvals) 

  if(!is.null(marks)) {
    fr_df <- fr_df %>% mutate(marks = as.factor(fx %in% marks))
  } else {
    fr_df <- fr_df %>% mutate(marks = as.factor(0))
  }

  ggplot(fr_df) + theme_minimal() + 
    geom_col(aes(x=fx, y=fvals, fill=marks)) +
    scale_x_continuous(name="Frequency (Hz)", limits=limits) +
    scale_y_continuous(name="Amplitude (uV)") +
    scale_fill_manual(values=c(hsv(0.0,0.0,0.6), hsv(0.0,0.0,0.0)), guide=FALSE)
}
limads/eegr documentation built on May 3, 2019, 3:21 p.m.