`plot_design_matrix` with the design matrix from `nilearn.glm.first_level.FirstLevelModel`

Should it be possible to use the plot_design_matrix() function with the design_matrices attributes from the fitted first level GLM? It looks like the design_matrices attribute does not have keys (i.e., column names).

avoid_model = FirstLevelModel(param_avoid_df['RepetitionTime'],
                              noise_model='ar1',
                              standardize=False,
                              hrf_model='spm + derivative + dispersion',
                              drift_model='cosine')
avoid_glm = avoid_model.fit(avoid_img, events_categ_avoid_df)
design_matrices = avoid_glm.design_matrices 
plot_design_matrix(design_matrices)

returns

AttributeError: 'list' object has no attribute 'keys'

Trying to follow this example.

I believe the problem is that design_matrices, as produced by FirstLevelModel, is a list of DataFrames, whereas the output of make_first_level_design_matrix is a DataFrame. If you want to plot the design matrices from FirstLevelModel, you just need to loop through the list, like so:

import matplotlib.pyplot as plt

# make a figure with one subplot per design matrix
fig, axes = plt.subplots(ncols=len(design_matrices))

for i_run, run_design_matrix in enumerate(design_matrices):
    plot_design_matrix(run_design_matrix, ax=axes[i_run])

    # alternatively, you could output each design matrix as
    # its own figure in files
    plot_design_matrix(run_design_matrix, output_file=f"run-{i_run}.png")

Alternatively, if there’s just one element in the design_matrices list, you can just do design_matrices = design_matrices[0] before calling plot_design_matrix in your original code.

Thank you! This worked.

@tsalo I think that this is an inconsistency, that just comes from the fact that design matrices were Numpy Arrays before we decided that they would be Dataframes. I’d be in favor of changing this. Do you agree ?
Bertrand

1 Like

I could be wrong, but I think the inconsistency is just in the variable name in the example. Since it’s a single data frame, it seems like it should be design_matrix.

Indeed, I read too quickly. Thx.
Bertrand