function [] = plotAverageResponse(rates, time, contrasts, filename)
[sort_contrasts, sort_idx] = sort(contrasts);

figure
set(gcf, 'paperunits', 'centimeters', 'papersize', [20 20], ...
    'paperposition', [0.0 0.0 20, 20], 'color', 'white')
axes = cell(size(sort_contrasts));
for i = 1:length(sort_contrasts)
    subplot(ceil(length(sort_contrasts)/2), 2, i);
    responses = rates{sort_idx(i)};
    avg_response = mean(responses, 2)';
    std_response = std(responses, [], 2)';
    f = fill([time fliplr(time)], [avg_response + std_response fliplr(avg_response - std_response)], ...
            'b', 'EdgeColor','none', 'displayname', 'std');
    alpha(f, 0.25)
    hold on
    plot(time, avg_response, 'b', 'displayname', 'average response')
    text(1.2, 500, sprintf('contrast: %i %', sort_contrasts(i)), ...
        'fontsize', 9, 'FontWeight', 'bold')
    xlim([time(1) time(end)])
    ylim([0, 600])
    set(gca, 'XTick', time(1):0.2:time(end), 'YTick', 0:200:600)
    if mod(i,2) == 1
        ylabel('firing rate [Hz]', 'fontsize', 11);
    else
        set(gca, 'yticklabels', []);
    end
    if i > length(sort_contrasts) - 2 
        xlabel('time [s]', 'fontsize', 11)
    else
        set(gca, 'xticklabels', []);
    end
   
    box('off')
    axes{i} = gca();
    if i == 1
        l = legend('show');
        l.FontSize = 9;
        l.Box = 'off';
        l.Orientation = 'horizontal';
        l.Position = [0.25, 0.96, .5, 0.01];
    end
end

axes{1}.Position = [axes{3}.Position(1) axes{2}.Position(2) ... 
    axes{2}.Position(3) axes{3}.Position(4)];
saveas(gcf, filename, 'pdf')