Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove space/gaps between continuous x-values in geom_raster

I am working with some time-frequency decomposed EEG data and want to produce a spectrogram-like figure using ggplot2. But, I end up with blank spaces between each of my time points.

Data <- read.csv(url("https://www.dropbox.com/s/al3cygigm86mr3s/Test_Spec_Data.csv?dl=0"))

If I create a vanilla geom_raster I get gaps in the x and y data:

ggplot(Data,aes(Times,Frequency)) +
  geom_raster(aes(fill = ERSP))

Default

If I make Frequency a factor, it fills in the y gap; but, the gaps along the x-axis remain:

  ggplot(Data,aes(Times,factor(round(Frequency,digits=1)))) +
  geom_raster(aes(fill = ERSP))

With y as factor

I can eliminate the gaps by making Times a factor.

enter image description here

But, managing scale_x_discrete with this many data points is cumbersome (note the x-axis labels). Also, these time data are continuous and not really factor-like.

geom_raster doesn't have a width argument like geom_bar and I can't see anything similar in the geom_raster documentation.

Is there a way to keep Times as continuous but remove the gaps between observations?

like image 661
JLC Avatar asked Oct 17 '22 06:10

JLC


1 Answers

There are gaps because there are not enough data (or more precisely, they are not evenly spaced).

Your "factor" transformation remove the gap because it remove the X or Y axis parts where data are missing. See in Y axis: ticks are evenly spaces but values are not (8.5-8.1=0.4, while 11.3-10.7=0.6, where you have you biggest gap).

I can see two solutions:

  • Interpolate data so your source data are evenly spaced
  • Use geom_tile instead of geom_raster and specify width and height parameters to "expand" your tiles and fill the gaps, as explained in the fourth example of the doc.
like image 151
Blacksad Avatar answered Oct 31 '22 17:10

Blacksad