Attachment 'plottingExampleCode_ljb_20191108.m'
Download 1 %lydia barnes, 20191107
2 %email: lydiabarnes01@gmail.com
3 %adapted from sneha shashidhara, 20181025
4
5 %this script contains example code for an introductory MATLAB visulisation
6 %course held at the MRC CBU, 08 Nov 2019.
7
8 %clear the command window, figures, and workspace
9 clc; close all; clear;
10
11 %in case of errors, make sure we can pause to see what went wrong
12 dbstop if error
13
14 %% scatter plot
15
16 %make some example data (or load your own data here)
17 x = linspace(0,1,100); %go from 0 to 1 in 100 steps
18 y = x + 0.1*rand(1,100); %copy x, then modify it by some random values between 0 and .1
19
20 %make an empty figure
21 figure
22
23 %->what does 'scatter' take as its first two inputs?
24
25 %plot!
26 scatter(x,y);
27
28 %add a least-squares fit line
29 lsline;
30
31 %->clear the plot, workspace, and command window
32
33 %% line plot
34
35 %make some example data
36 x = linspace(0,360,100); %0:360 in 100 steps
37 y = sind(x);
38 z = cosd(x);
39
40 %set your colours. MATLAB plots expect colours in a vector of three values
41 %between 0 and 1, indicating red, green, and blue intensities
42 red=[1 0 0];
43 green=[0 1 0];
44 blue=[0 0 1];
45 black=[0 0 0];
46 white=[1 1 1];
47 %->choose your own three colours! ie purple = [.5 0 .5]...
48
49 %make an empty figure. this time, store a 'handle' to the figure
50 h = figure;
51 %->look at h to see what 'properties' a figure automatically has
52
53 %->learn about name-value pairs
54
55 %plot!
56 plot(x,y,'Color',red)
57
58 %'hold' the plot so that the next plot commands layer over the top of this
59 %one
60 hold on
61
62 %make some fresh data
63 plot(x,z,'Color',blue);
64
65 %describe the plot contents
66 title('trigonometry','FontSize',20);
67 xlabel('angle in degrees');
68 ylabel('trig functions');
69 legend('sine','cosine','Location','best'); %put a legend where it fits best
70 legend boxoff
71
72 %because we have a handle for the figure, we can ask matlab to save
73 %everything from that handle to an image file
74 saveas(h,'trigLinePlot');
75
76 %% barplots
77
78 %make some example data
79 % assume we've collected reaction times from 10 participants for 3
80 % different tasks, each of which has an easy and a difficult version.
81 % we'll organise our data into one subjects x tasks matrix for easy, and
82 % another subjects x tasks matrix for the hard condition:
83 x = randi(10,[10,3]); %x = easy. get integers between 0 and 10, for 10 subjects (rows) and 3 tasks (columns)
84 y = x + randi(3,[10,3]); %y = hard. assume this evoked slightly larger responses than the easy condition.
85 % get the group average of each condition
86 data = [mean(x,1); mean(y,1)];
87 % estimate the standard error (the standard deviation/sq root of n)
88 % of the group means
89 errorData = [std(x,1)/sqrt(size(x,1)); std(y,1)/sqrt(size(y,1))];
90 %-> view your data matrices
91
92 %make a new figure
93 h = figure; %store the figure handle in h
94
95 %plot
96 b = bar(data); %store the plot handle in b
97 hold on %make sure subsequent plotting commands apply to this figure
98 %->look at b's properties by typing b into the command window
99 %->what properties are in h (the figure handle) vs b (the plot handle)?
100
101 %set the colours for each task
102 set(b(1),'FaceColor',blue);
103 set(b(2),'FaceColor',green);
104 set(b(3),'FaceColor',red);
105
106 %label your figure and axes
107 title('reaction times across three cognitive tasks (n=10)','FontSize',15);
108 xlabel('conditions','FontSize',15);
109 ylabel('RT (s)','FontSize',15);
110
111 %get the axis handle
112 ax=gca;
113 %->look at the axis handle
114 %->what properties does the axis (ax) have? compare to the figure
115 %properties in h
116
117 %modify the axis properties
118 set(ax,'XTick',[1, 2]) %only put ticks at 1 and 2
119 set(ax,'XTickLabel',{'easy','hard'}) %label those ticks with our conditions
120
121 %add error bars
122 % record where the centre of each bar is along the x-axis
123 X = [1-(2/9) 1 1+(2/9); 2-(2/9) 2 2+(2/9)];
124 % use the errorbar function to plot the standard errors you calculated
125 % earlier. inputs are the x-axis positions, y-axis positions (our group
126 % means), and the standard errors for each bar
127 % (by default, errorbar plots bars 2*the standard error in either
128 % direction)
129 eb = errorbar(X,data,errorData,'.','Color',black);
130 %-> use name-value pairs to set the width of the errorbars
131 set(eb,'LineWidth',1.5)
132
133 %do a ttest! OR invent a p-value and skip this step...
134 % average the three tasks to get one column of values each for the easy
135 % and hard conditions
136 allxdata = mean(x,2); %easy
137 allydata = mean(y,2); %hard
138 % use the ttest function. inputs are condition 1 and condition 2 as
139 % vectors. outputs are [h,p,stats], where h is 1 if you can reject the
140 % null at alpha = .05, and p is the p-value. discard h but store p
141 [~,p] = ttest(allxdata,allydata);
142
143 p=.01; %make a p-value
144
145 %plot a line indicating what we compared, along with the p-value
146 % calculate the highest value on the plot: the largest group mean plus
147 % its error bar
148 ymax = max(max(data)) + max(max(errorData));
149 % plot a line at that height (ie the top of the plot), stretching between
150 % our two conditions
151 line([1 2],[ymax ymax],'linewidth',2,'Color',black);
152 % add text for our p-value
153 t=text(1.5,ymax,sprintf('p = %.2f',p));
154 %->change Vertical Alignment so that the line and text don't overlap
155 %->adjust the font size
156 t.FontSize=15;
157 t.HorizontalAlignment='center';
158 t.VerticalAlignment='bottom';
159
160 %-> use ylim to adjust the y-axis limits to make room for the p-value
161 ylim([0 ymax+1])
162
163 %save the plot
164 %->look at "help saveas" and work out how to save the figure as a jpeg
165 saveas(h,'responseTimesGrpBarPlot.jpg');
166
167
168 %% subplots
169
170 %make a new figure
171 h = figure;
172
173 %make sure the subsequent plotting commands are applied to this figure
174 hold on;
175
176 %we're going to reuse the data from the previous barplot. rather than take
177 %the group average, we'll plot each subject on their own 'subplot' within
178 %this figure.
179
180 %->find out how many subjects there are with the size function. remember,
181 %we had one subject per row in the data matrices x and y.
182 nsubjects = size(x,1);
183
184 %make an empty array of axes with 'gobjects' (for speed - not essential)
185 ax = gobjects(1,nsubjects); %1 row, a column per subject
186
187 %loop through each subject
188 for subjid = 1:nsubjects %as the index increases from 1 to the number of subjects
189
190 %select this subject's data from our easy and hard condition matrices
191 data = [x(subjid,:); y(subjid,:)]; %row 1 is from x, row 2 is from y
192
193 %->use help look at the first three inputs we can give the subplot function
194
195 %make a subplot for this person, and store its handle in the empty axis array
196 %we made earlier
197 % subplot breaks a figure into parts. its first two inputs dictate
198 % how many rows and columns of subplots you want: in our case, 2
199 % rows, 5 columns. the third input selects which subplot you want to
200 % work with (moving left-right, top-bottom, as though you're reading)
201 ax(subjid) = subplot(2,5,subjid);
202
203 %now that we've selected a subplot, plot this subject's data there
204 b=bar(data);
205
206 %->use your favourite colours for the three bars
207
208 %label the plot with this subject's ID
209 title(sprintf('subject %d',subjid));
210 end
211
212 %label the full plot
213 suptitle('all subjects');
214
215 %calculate the group range and use it to set the y-axis limits
216 lower=min([min(x),min(y)])-1;
217 upper=max([max(x),max(y)])+1;
218 set(ax,'ylim',[lower upper]);
219
220
221 %% matrices
222
223 %make some data
224 x=randn(5,5); %fill a 5x5 matrix with random values
225 %->when would we want to plot full matrices?
226
227 %make a new plot
228 figure
229 imagesc(x); %treat the matrix as an image, giving each value a color based on its magnitude
230 colorbar; %show the color scale
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.