Search code examples
rplotggplot2trace

R plot Fire Trace


Just getting started with R and would value your input on this question.

What I'm trying to achieve is that:

  1. X axis has all values for "Timestamp"(from 0 to 9)
  2. Y axis has all values for "NID"(from 0 to 3)
  3. There are "dots" at the coordinates of ("Timestamp","NID") where the attribute "Fired" = 1.

The source data has the following format:

dat = structure(list(TimeStamp = c(0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 
1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 
4L), NID = c(0L, 1L, 2L, 3L, 4L, 0L, 1L, 2L, 3L, 4L, 0L, 1L, 
2L, 3L, 4L, 0L, 1L, 2L, 3L, 4L, 0L, 1L, 2L, 3L, 4L), NumberSynapsesTotal = c(2L, 
2L, 3L, 2L, 4L, 2L, 2L, 3L, 2L, 4L, 2L, 2L, 3L, 2L, 4L, 2L, 2L, 
3L, 2L, 4L, 2L, 2L, 3L, 2L, 4L), NumberActiveSynapses = c(1L, 
2L, 1L, 2L, 3L, 1L, 2L, 1L, 1L, 0L, 1L, 2L, 1L, 1L, 0L, 1L, 2L, 
1L, 1L, 0L, 1L, 0L, 0L, 1L, 0L), Fires = c(1L, 1L, 1L, 1L, 0L, 
1L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 1L, 
0L, 1L, 0L, 0L)), row.names = c(NA, 25L), class = "data.frame")

I tried to apply a filter, but it shows a subset of data for those "ID"s, where there is value 1 for the attribute "Fired" (no all values for the axes):

dat %>%
filter(dat$Fires == 1) %>%
ggplot(aes(x = dat$TimeStamp[dat$Fires == 1], y = dat$NID[dat$Fires == 1])) +
geom_point()

Case 1

Alternatively, I get all existing values for the attributes "Timestamp" and "NID" by using the following code:

 plot(dat$TimeStamp, dat$NID,
 xlab = "Time", ylab = "Neuron ID")
 title(main = "Fire Trace Plot")

so the picture looks in the following way:

enter image description here

Finally, from the comment below I modified the code to:

ggplot(dat, aes(x = TimeStamp, y = NID) , xlab = "Time", ylab ="Neuron 
ID") +
geom_blank() +
geom_point(dat = filter(dat) +
#title(main = "Fire Trace Plot")
scale_x_continuous(breaks = F_int_time_breaks(1) ) 

Is that the case that i should build two charts on one plot? Thank you!


Solution

  • With ggplot2, never use data$ inside aes(), just use the column names. Similarly, the dplyr functions like filter should not be used with data$ - they know to look in the data frame for the column.

    I think you want to build your ggplot with the full data, so the axes get set to cover the full data (we force this by adding a geom_blank() layer), and it is only the point layer that should be subset:

    # create some sample data (it is nice if you provide this in the question)
    dat = expand.grid(Timestamp = 0:9, NID = 0:3)
    dat$Fires = ifelse(dat$NID == 2, 1, 0)
    
    # make the plot
    ggplot(dat, aes(x = Timestamp, y = NID)) +
        geom_blank() +
        geom_point(dat = filter(dat, Fires == 1))
    

    enter image description here