

%lydia barnes, 20191107
%email: lydiabarnes01@gmail.com
%adapted from sneha shashidhara, 20181025

%this script contains example code for an introductory MATLAB visulisation
%course held at the MRC CBU, 08 Nov 2019. 

%clear the command window, figures, and workspace
clc; close all; clear; 

%in case of errors, make sure we can pause to see what went wrong
dbstop if error

%% scatter plot

%make some example data (or load your own data here)
x = linspace(0,1,100); %go from 0 to 1 in 100 steps
y = x + 0.1*rand(1,100); %copy x, then modify it by some random values between 0 and .1

%make an empty figure
figure

%->what does 'scatter' take as its first two inputs?

%plot!
scatter(x,y);

%add a least-squares fit line
lsline;

%->clear the plot, workspace, and command window

%% line plot

%make some example data
x = linspace(0,360,100); %0:360 in 100 steps
y = sind(x); 
z = cosd(x);

%set your colours. MATLAB plots expect colours in a vector of three values
%between 0 and 1, indicating red, green, and blue intensities
red=[1 0 0];
green=[0 1 0];
blue=[0 0 1];
black=[0 0 0];
white=[1 1 1];
%->choose your own three colours! ie purple = [.5 0 .5]...

%make an empty figure. this time, store a 'handle' to the figure
h = figure;
%->look at h to see what 'properties' a figure automatically has

%->learn about name-value pairs

%plot!
plot(x,y,'Color',red)

%'hold' the plot so that the next plot commands layer over the top of this
%one
hold on

%make some fresh data
plot(x,z,'Color',blue);

%describe the plot contents
title('trigonometry','FontSize',20);
xlabel('angle in degrees');
ylabel('trig functions');
legend('sine','cosine','Location','best'); %put a legend where it fits best
legend boxoff

%because we have a handle for the figure, we can ask matlab to save
%everything from that handle to an image file
saveas(h,'trigLinePlot');

%% barplots

%make some example data
%   assume we've collected reaction times from 10 participants for 3
%   different tasks, each of which has an easy and a difficult version.
%   we'll organise our data into one subjects x tasks matrix for easy, and
%   another subjects x tasks matrix for the hard condition:
x = randi(10,[10,3]); %x = easy. get integers between 0 and 10, for 10 subjects (rows) and 3 tasks (columns)
y = x + randi(3,[10,3]); %y = hard. assume this evoked slightly larger responses than the easy condition.
%   get the group average of each condition
data = [mean(x,1); mean(y,1)];
%   estimate the standard error (the standard deviation/sq root of n)
%   of the group means
errorData = [std(x,1)/sqrt(size(x,1)); std(y,1)/sqrt(size(y,1))];
%-> view your data matrices

%make a new figure
h = figure; %store the figure handle in h

%plot
b = bar(data); %store the plot handle in b
hold on %make sure subsequent plotting commands apply to this figure
%->look at b's properties by typing b into the command window
%->what properties are in h (the figure handle) vs b (the plot handle)?

%set the colours for each task
set(b(1),'FaceColor',blue);
set(b(2),'FaceColor',green);
set(b(3),'FaceColor',red);

%label your figure and axes
title('reaction times across three cognitive tasks (n=10)','FontSize',15);
xlabel('conditions','FontSize',15); 
ylabel('RT (s)','FontSize',15);

%get the axis handle
ax=gca; 
%->look at the axis handle 
%->what properties does the axis (ax) have? compare to the figure
%properties in h

%modify the axis properties
set(ax,'XTick',[1, 2]) %only put ticks at 1 and 2
set(ax,'XTickLabel',{'easy','hard'}) %label those ticks with our conditions

%add error bars
%   record where the centre of each bar is along the x-axis
X = [1-(2/9) 1 1+(2/9); 2-(2/9) 2 2+(2/9)];
%   use the errorbar function to plot the standard errors you calculated
%   earlier. inputs are the x-axis positions, y-axis positions (our group 
%   means), and the standard errors for each bar
%   (by default, errorbar plots bars 2*the standard error in either
%   direction)
eb = errorbar(X,data,errorData,'.','Color',black); 
%-> use name-value pairs to set the width of the errorbars
set(eb,'LineWidth',1.5)

%do a ttest! OR invent a p-value and skip this step...
%   average the three tasks to get one column of values each for the easy
%   and hard conditions
allxdata = mean(x,2); %easy
allydata = mean(y,2); %hard
%   use the ttest function. inputs are condition 1 and condition 2 as
%   vectors. outputs are [h,p,stats], where h is 1 if you can reject the
%   null at alpha = .05, and p is the p-value. discard h but store p
[~,p] = ttest(allxdata,allydata);

p=.01; %make a p-value

%plot a line indicating what we compared, along with the p-value
%   calculate the highest value on the plot: the largest group mean plus
%   its error bar
ymax = max(max(data)) + max(max(errorData));
%   plot a line at that height (ie the top of the plot), stretching between
%   our two conditions
line([1 2],[ymax ymax],'linewidth',2,'Color',black);
%   add text for our p-value
t=text(1.5,ymax,sprintf('p = %.2f',p));
%->change Vertical Alignment so that the line and text don't overlap
%->adjust the font size
t.FontSize=15;
t.HorizontalAlignment='center';
t.VerticalAlignment='bottom';

%-> use ylim to adjust the y-axis limits to make room for the p-value
ylim([0 ymax+1])

%save the plot
%->look at "help saveas" and work out how to save the figure as a jpeg
saveas(h,'responseTimesGrpBarPlot.jpg');


%% subplots

%make a new figure
h = figure;

%make sure the subsequent plotting commands are applied to this figure
hold on;

%we're going to reuse the data from the previous barplot. rather than take
%the group average, we'll plot each subject on their own 'subplot' within
%this figure.

%->find out how many subjects there are with the size function. remember,
%we had one subject per row in the data matrices x and y.
nsubjects = size(x,1);

%make an empty array of axes with 'gobjects' (for speed - not essential)
ax = gobjects(1,nsubjects); %1 row, a column per subject

%loop through each subject
for subjid = 1:nsubjects %as the index increases from 1 to the number of subjects
    
    %select this subject's data from our easy and hard condition matrices
    data = [x(subjid,:); y(subjid,:)]; %row 1 is from x, row 2 is from y
    
    %->use help look at the first three inputs we can give the subplot function
    
    %make a subplot for this person, and store its handle in the empty axis array
    %we made earlier
    %   subplot breaks a figure into parts. its first two inputs dictate
    %   how many rows and columns of subplots you want: in our case, 2
    %   rows, 5 columns. the third input selects which subplot you want to
    %   work with (moving left-right, top-bottom, as though you're reading)
    ax(subjid) = subplot(2,5,subjid);
    
    %now that we've selected a subplot, plot this subject's data there
    b=bar(data);
    
    %->use your favourite colours for the three bars
    
    %label the plot with this subject's ID
    title(sprintf('subject %d',subjid));
end

%label the full plot
suptitle('all subjects');

%calculate the group range and use it to set the y-axis limits
lower=min([min(x),min(y)])-1;  
upper=max([max(x),max(y)])+1;
set(ax,'ylim',[lower upper]);


%% matrices

%make some data
x=randn(5,5); %fill a 5x5 matrix with random values
%->when would we want to plot full matrices?

%make a new plot
figure
imagesc(x); %treat the matrix as an image, giving each value a color based on its magnitude
colorbar; %show the color scale

