Basic tips for creating visually appealing graphics in ...Basic tips for creating visually appealing...

23
Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM] Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab Contents Constructing a simple plot. Beautifying a plot. Recap: basic parameters to control the appearence of a plot. Choosing colors. Option I: picking colors manually. Choosing colors. Option II: Using pre-defined colormaps. Choosing colors. Option III: Creating your own colormaps. Displaying multiple datasets on a plot. MATLAB® is a software and programing environment that allows the manipulation and visualization of data. Using a simple scripting language, one can combine numerical computations with complex graphical displays, which makes MATLAB® a very useful tool for data analysis and exploration. However, despite all its versatility, the default graphic options from MATLAB® are not very appealing, either for data exploration or further publication. Below, I will give a series of simple tips to improve graphics in MATLAB®. Constructing a simple plot. We will start by creating a very simple data set. close all; % Close previous plots. clear; % Delete all variables from the workspace. clc; % Delete any past commands from the command line. N = 100; X = 1:N; Y = 1:N; The code above generates two equal numeric arrays, X and Y, that contain N integer numbers (from 1 to N). Then, we can add some noise to the data: X = X + 0.5*N*(rand(1,N)-0.5); % rand(A,B) generates an array with A rows and B columns filled Y = Y + 0.5*N*(rand(1,N)-0.5); % with random numbers uniformly distributed between 0 and 1. The code above adds a random number, ranging from -0.25*N to 0.25*N , to each element of X and Y. We can display the data using the plot function: fh = figure; % Open a new figure, and creates the variable fh that % contains all the properties of the figure. hold on; % Hold the current plot and all axis properties so that % subsequent graphing commands add to the existing graph. plot(X,Y,'o'); % Plots X vs Y, using circles 'o' as markers.

Transcript of Basic tips for creating visually appealing graphics in ...Basic tips for creating visually appealing...

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Basic tips for creating visually appealing graphics inMATLAB®, from the Golding LabContents

    Constructing a simple plot.Beautifying a plot.Recap: basic parameters to control the appearence of a plot.Choosing colors. Option I: picking colors manually.Choosing colors. Option II: Using pre-defined colormaps.Choosing colors. Option III: Creating your own colormaps.Displaying multiple datasets on a plot.

    MATLAB® is a software and programing environment that allows the manipulation andvisualization of data. Using a simple scripting language, one can combine numericalcomputations with complex graphical displays, which makes MATLAB® a very useful toolfor data analysis and exploration. However, despite all its versatility, the default graphicoptions from MATLAB® are not very appealing, either for data exploration or furtherpublication. Below, I will give a series of simple tips to improve graphics in MATLAB®.

    Constructing a simple plot.

    We will start by creating a very simple data set.

    close all; % Close previous plots.clear; % Delete all variables from the workspace.clc; % Delete any past commands from the command line.

    N = 100;X = 1:N;Y = 1:N;

    The code above generates two equal numeric arrays, X and Y, that contain N integer numbers(from 1 to N). Then, we can add some noise to the data:

    X = X + 0.5*N*(rand(1,N)-0.5); % rand(A,B) generates an array with A rows and B columns filledY = Y + 0.5*N*(rand(1,N)-0.5); % with random numbers uniformly distributed between 0 and 1.

    The code above adds a random number, ranging from -0.25*N to 0.25*N , to each element ofX and Y. We can display the data using the plot function:

    fh = figure; % Open a new figure, and creates the variable fh that % contains all the properties of the figure.

    hold on; % Hold the current plot and all axis properties so that % subsequent graphing commands add to the existing graph.

    plot(X,Y,'o'); % Plots X vs Y, using circles 'o' as markers.

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Now, let's calculate the mean and standard error over finite windows of the data:

    n_bins = 20;x_mean = zeros(n_bins,1); % zeros(A,B) generates an array with A rows and B columns filled with zeros.x_sem = zeros(n_bins,1);y_mean = zeros(n_bins,1);y_sem = zeros(n_bins,1);

    for ii = 1:n_bins

    % Select the index of the data sets to be merged into one bin. bin_idx = (1:N/n_bins) + (ii-1)*N/n_bins;

    % Mean X value in the bin. x_mean(ii) = mean(X(bin_idx)); % mean(A): average or mean value of A.

    % Standard Error of the Mean (SEM). x_sem(ii) = std(X(bin_idx))/sqrt(numel(bin_idx)); % sqrt(A): square root of A. % numel(A): number of elements of array A. (a simple variable is considered an 1x1 array) % std(A): standard deviation of A.

    % Mean Y value in the bin. y_mean(ii) = mean(Y(bin_idx));

    % Standard Error of the Mean (SEM). y_sem(ii) = std(Y(bin_idx))/sqrt(numel(bin_idx));

    end

    We can now overlap the average data plus error bars on top of the raw data:

    errorbar(x_mean,y_mean,y_sem,'ro');

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    MATLAB® has an extensive Curve Fitting Toolbox™. Another feature of a simple plot is toadd a simple model trying to describe the data. For illustration, we can try to fit the raw datawith a linear model:

    % set fitting parametersft = fittype( 'poly1' ); % Define the type of function used to fit. In this case, a polynomial of grade 1, or y = p1*X + p2.opts = fitoptions( ft ); % Generate structure array with paramaters for the fit.opts.Lower = [-Inf -Inf]; % Lower bounds for p1 and p2 parameters.opts.Upper = [Inf Inf]; % Upper bounds for p1 and p2 parameters.

    % Fit model to data.[fitresult, gof] = fit( X', Y', ft, opts );

    And we can now add the fit to the plot:

    xfit = -0.1*N:1.1*N;yfit = fitresult.p1*xfit + fitresult.p2;

    % Calculate the standard error in the parameters.ci = confint(fitresult,0.95); % Get the 95% confidence intervals (CI) for the fit.p1_se = (ci(2,1)-ci(1,1))/4; % CI is approximately 2*SEM.p2_se = (ci(1,2)-ci(2,2))/4; % for more info see https://en.wikipedia.org/wiki/Confidence_interval.

    plot(xfit,yfit,'k-');

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Beautifying a plot.

    One of the main concepts in graphical style is Salience. Salience is a visual quality that setsan object apart from its surroundings (Bang Wong, Nature Methods 2010). The salience ofan object can be modified by changing attributes such as color, thickness (of lines) and size.The plot above, made using some of the default colors available in MATLAB®, illustrateswhy a poor color selection needs to be avoided: it not only makes things look ugly, but mostimportantly, makes graphics hard to understand.

    Below is an improved version of the figure above, were we changed the color, thickness andsize of the markers. In the original plot, the three groups of objects on display (the raw data,the moving average and the fit) had saturated colors that are very hard to distinguish fromeach other. One can improve the plot by decreasing the salience of the raw data (in the casebelow, by using a light gray color) and then keeping the colors of the average data and the fit:

    fh = figure; hold onset(fh,'color','w'); % Define the background color of the figure. The default is gray.

    % Plot data and set different object properties, like, MarkerSize% MarkerFaceColor, MarkerEdgeColor and LineWidth. p1h, e1h and p2h are% handles to the plots that can be used later to modify the plots further.

    p1h = plot(X,Y,'o','MarkerSize',5,... 'MarkerFaceColor',[.85 .85 .85],... 'MarkerEdgeColor','none');

    e1h = errorbar(x_mean,y_mean,y_sem,'ko',... 'MarkerSize',7,... 'MarkerFaceColor','k',... 'MarkerEdgeColor','none',... 'LineWidth',2);

    p2h = plot(xfit,yfit,'r-',... 'LineWidth',2);

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    I would argue that the new, "beautified" plot is clearer than the original, unformated plot. Thechanges made are listed below:

    We increased the width of the fit and average lines to 2 pt. This increase the salience ofthe data with respect to the figure axis (which remains to be 0.5 pt).

    We decreased the salience of the raw data with respect of the average data byincreasing the brighness of the color.

    After improving the general appearance of the plot, we need to add some comments to helpmake sense of the data. The most typical annotations are the labels of the X and Y axis, aswell as adding a brief explanatory title:

    fontsize = 13;xlabel('X variable (A.U.)','fontsize',fontsize);ylabel('Y variable (A.U.)','fontsize',fontsize);title(['X and Y are linearly correlated (\rho = ' num2str(corr(X',Y'),'%1.3f') ')' ],'fontsize',fontsize);

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Given that both axes have the same numerical range, we can adjust the axes aspect-ratio:

    axis square; % Adjust the axes to have the same size in the X and Y dimensions.

    Additionally, we can adjust the limits of the axes:

    xlim([-0.1 1.1]*N); % xlim([MIN MAX]);ylim([-0.1 1.1]*N);

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Another important concept of graphical style is Simplicity. If possible, it is important toremove unnecesary elements from a figure. In the case above, each axis has many tick marks.We can adjust which ticks and labels to show, and evaluate whether the figure has improved:

    % gca: get handle of the current axis.set(gca,'XTick',[0 N/2 N],... 'XTickLabel',{'0',num2str(N/2),num2str(N)},... 'YTick',[0 N/2 N],... 'YTickLabel',{'0',num2str(N/2),num2str(N)},... 'fontsize',12);

    We can also try closing the bounding box of the plot:

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    box on;

    Finally, we can add an explanatory legend describing what is being plotted.

    lh = legend([p1h e1h p2h],'raw data',... lh = legend handle. 'moving average',... ['Y = p_1*X + p_2' sprintf('\n') ... 'p_1 = ' num2str(fitresult.p1,'%1.2f') '\pm' num2str(p1_se,'%1.2f') sprintf('\n')... 'p_2 = ' num2str(fitresult.p2,'%1.2f') '\pm' num2str(p2_se,'%1.2f')]);

    set(lh,'Location','NorthWest','Fontsize',10); % Set the properties of the legend.

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Recap: basic parameters to control the appearence of a plot.

    Below is a short script that includes all the options that we used to improve the appearence ofour plot. It can be adapted to fit your plotting needs:

    % 1. Set the figure propertiesfh = figure; % Open figure and create legend handle fh.hold on; % Add multiple plots to the current figure.

    set(fh,'color','w',... % Set background color of the outside of figure. gray is default. White (w) looks better. 'units','inches',... % Define units for the position of the figure. 'position',[.2 .5 9 9]); % % Position of the figure on the screen, % [Distance to left of screen ... % Distance to bottom of screen ... % Width of the figure ... % Height of the figure ]

    % 2. Set the properties of the plot

    p1h = plot(rand(100,1),rand(100,1),'o',... % Posible markers = o,s,d,v,^,.,*. 'MarkerSize',15,... % Size of marker. 'MarkerFaceColor',[.85 .85 .85],... % Color of the marker. 'None' is the default. 'MarkerEdgeColor',[0.88 0.28 0.44],... % Color of the edge line of the marker. 'None' to not show. 'LineWidth',3); % With of the line in the edge of the marker.

    % 3. Set the properties of the plot axis, add annotations% Below are the most common options (the ones I use more often)% for a more exhaustive list, see:% http://www.mathworks.com/help/matlab/ref/axes-properties.htmlset(gca,... 'XTick', [0 .25 .50 .75 1],... % List of positions for the X ticks. 'XTickLabel',{'0','.25','.50','.75','1'},... % List of labels for the X ticks. 'XColor', [0.18 0.56 1.00],... % Color of X axis, ticks, ticklabels, and labels. 'XLim', [0 1],... % Range of the of X axis on display. 'XDir', 'normal',... % Direction of the axis. 'normal' is ascendent. 'YTick', [0 .50 1],... % List of positions for the Y ticks. 'YTickLabel',{'0','.50','1'},... % List of labels for the Y ticks. 'YColor', [0.20 0.80 0.20],... % Color of Y axis, ticks, ticklabels, and labels. 'YLim', [0 1],... % Range of the of Y axis on display. 'Ydir', 'reverse',... % Direction of the Y axis. 'reverse' is descendent. 'FontSize', 20,... % Font size of the Xtick and Y tick labels. 'Linewidth', 2); % Width of the axes and ticks. 0.5 is the default.

    axis square; % Define axes aspect ratio and visibility. Use 'axis off' to not show axis.xlabel('X label','fontsize',24); % Add Explanatory label to X axis.ylabel('Y label','fontsize',24); % Add Explanatory label to Y axis.title('Title', 'fontsize',30); % Add explanatory Title to the figure.box on; % Add (on) or remove (off) the lines on the top and left of the axis.

    % 4. Add a legend and set its properties

    lh = legend(p1h,'raw data'); % Add explanatory legend.

    set(lh,'Location','NorthWest',... % Define location of the legend in the axis frame of reference. 'Fontsize',25); % Legend font size.

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Choosing colors. Option I: picking colors manually.

    Color is an important tool to modify the salience of objects. There are multiple ways tochoose colors. The first and simplest, is to choose manually from a color picker inside agraphical program like illustrator. I like to visit this website:http://cloford.com/resources/colours/500col.htm , choose some colors that I find appealing,and try to modify them later in illustrator. Below, I created an array with the RGB codes forall the colors from the website (without the gray and black colors) to display them insideMATLAB®:

    C = [ ...

    http://cloford.com/resources/colours/500col.htm

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    153 50 204; 191 62 255; 178 58 238; 154 50 205; 104 34 139; 75 0 130; 138 43 226; 155 48 255; 145 44 238; 125 38 205; ... 85 26 139; 147 112 219; 171 130 255; 159 121 238; 137 104 205; 93 71 139; 72 61 139; 132 112 255; 123 104 238; 106 90 205; ... 131 111 255; 122 103 238; 105 89 205; 71 60 139; 248 248 255; 230 230 250; 0 0 255; 0 0 238; 0 0 205; 0 0 139; ... 0 0 128; 25 25 112; 61 89 171; 65 105 225; 72 118 255; 67 110 238; 58 95 205; 39 64 139; 100 149 237; 176 196 222; ... 202 225 255; 188 210 238; 162 181 205; 110 123 139; 119 136 153; 112 128 144; 198 226 255; 185 211 238; 159 182 205; 108 123 139; ... 30 144 255; 28 134 238; 24 116 205; 16 78 139; 240 248 255; 70 130 180; 99 184 255; 92 172 238; 79 148 205; 54 100 139; ... 135 206 250; 176 226 255; 164 211 238; 141 182 205; 96 123 139; 135 206 255; 126 192 238; 108 166 205; 74 112 139; 135 206 235; ... 0 191 255; 0 178 238; 0 154 205; 0 104 139; 51 161 201; 173 216 230; 191 239 255; 178 223 238; 154 192 205; 104 131 139; ... 176 224 230; 152 245 255; 142 229 238; 122 197 205; 83 134 139; 0 245 255; 0 229 238; 0 197 205; 0 134 139; 95 158 160; ... 0 206 209; 240 255 255; 224 238 238; 193 205 205; 131 139 139; 224 255 255; 209 238 238; 180 205 205; 122 139 139; 187 255 255; ... 174 238 238; 150 205 205; 102 139 139; 47 79 79; 151 255 255; 141 238 238; 121 205 205; 82 139 139; 0 255 255; 0 238 238; ... 0 205 205; 0 139 139; 0 128 128; 72 209 204; 32 178 170; 3 168 158; 64 224 208; 128 138 135; 0 199 140; 127 255 212; ... 118 238 198; 102 205 170; 69 139 116; 0 250 154; 245 255 250; 0 255 127; 0 238 118; 0 205 102; 0 139 69; 60 179 113; ... 84 255 159; 78 238 148; 67 205 128; 46 139 87; 0 201 87; 189 252 201; 61 145 64; 240 255 240; 224 238 224; 193 205 193; ... 131 139 131; 143 188 143; 193 255 193; 180 238 180; 155 205 155; 105 139 105; 152 251 152; 154 255 154; 144 238 144; 124 205 124; ... 84 139 84; 50 205 50; 34 139 34; 0 255 0; 0 238 0; 0 205 0; 0 139 0; 0 128 0; 0 100 0; 48 128 20; ... 124 252 0; 127 255 0; 118 238 0; 102 205 0; 69 139 0; 173 255 47; 202 255 112; 188 238 104; 162 205 90; 110 139 61; ... 85 107 47; 107 142 35; 192 255 62; 179 238 58; 154 205 50; 105 139 34; 255 255 240; 238 238 224; 205 205 193; 139 139 131; ... 245 245 220; 255 255 224; 238 238 209; 205 205 180; 139 139 122; 250 250 210; 255 255 0; 238 238 0; 205 205 0; 139 139 0; ... 128 128 105; 128 128 0; 189 183 107; 255 246 143; 238 230 133; 205 198 115; 139 134 78; 240 230 140; 238 232 170; 255 250 205; ... 238 233 191; 205 201 165; 139 137 112; 255 236 139; 238 220 130; 205 190 112; 139 129 76; 227 207 87; 255 215 0; 238 201 0; ... 205 173 0; 139 117 0; 255 248 220; 238 232 205; 205 200 177; 139 136 120; 218 165 32; 255 193 37; 238 180 34; 205 155 29; ... 139 105 20; 184 134 11; 255 185 15; 238 173 14; 205 149 12; 139 101 8; 255 165 0; 238 154 0; 205 133 0; 139 90 0; ... 255 250 240; 253 245 230; 245 222 179; 255 231 186; 238 216 174; 205 186 150; 139 126 102; 255 228 181; 255 239 213; 255 235 205; ... 255 222 173; 238 207 161; 205 179 139; 139 121 94; 252 230 201; 210 180 140; 156 102 31; 255 153 18; 250 235 215; 255 239 219; ... 238 223 204; 205 192 176; 139 131 120; 222 184 135; 255 211 155; 238 197 145; 205 170 125; 139 115 85; 255 228 196; 238 213 183; ... 205 183 158; 139 125 107; 227 168 105; 237 145 33; 255 140 0; 255 127 0; 238 118 0; 205 102 0; 139 69 0; 255 128 0; ... 255 165 79; 238 154 73; 205 133 63; 139 90 43; 250 240 230; 255 218 185; 238 203 173; 205 175 149; 139 119 101; 255 245 238; ... 238 229 222; 205 197 191; 139 134 130; 244 164 96; 199 97 20; 210 105 30; 255 127 36; 238 118 33; 205 102 29; 139 69 19; ... 41 36 33; 255 125 64; 255 97 3; 138 54 15; 160 82 45; 255 130 71; 238 121 66; 205 104 57; 139 71 38; 255 160 122; ... 238 149 114; 205 129 98; 139 87 66; 255 127 80; 255 69 0; 238 64 0; 205 55 0; 139 37 0; 94 38 18; 233 150 122; ... 255 140 105; 238 130 98; 205 112 84; 139 76 57; 255 114 86; 238 106 80; 205 91 69; 139 62 47; 138 51 36; 255 99 71; ... 238 92 66; 205 79 57; 139 54 38; 250 128 114; 255 228 225; 238 213 210; 205 183 181; 139 125 123; 255 250 250; 238 233 233; ... 205 201 201; 139 137 137; 188 143 143; 255 193 193; 238 180 180; 205 155 155; 139 105 105; 240 128 128; 205 92 92; 255 106 106; ... 238 99 99; 139 58 58; 205 85 85; 165 42 42; 255 64 64; 238 59 59; 205 51 51; 139 35 35; 178 34 34; 255 48 48; ... 238 44 44; 205 38 38; 139 26 26; 255 0 0; 238 0 0; 205 0 0; 139 0 0; 128 0 0; 142 56 142; 113 113 198; ... 125 158 192; 56 142 142; 113 198 113; 142 142 56; 197 193 170; 198 113 113; ]/255;

    I display the colors below, using the plot function and a for loop:

    fh = figure; hold on;set(fh,'color','w')

    counter = 0;for ii = 1:20 for jj = 1:20

    counter = counter + 1;

    plot(ii,jj,'s','markersize',14,... 'markeredgecolor','none',...

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    'markerfacecolor',C(counter,:));

    if counter == size(C,1), break, end end

    if counter == size(C,1), break, endend

    xlim([0 21]);ylim([0 21]);axis offaxis square;title(['Colors from ' sprintf('\n') 'http://cloford.com/resources/colours/500col.htm']);

    Choosing colors. Option II: Using pre-defined colormaps.

    Other good source of colors is the website http://colorbrewer2.org/. One can download theMATLAB® version from the MathWorks File Exchange:https://www.mathworks.com/matlabcentral/fileexchange/34087-cbrewer---colorbrewer-schemes-for-matlab. Once you download the program to your computer, you can add thefolder containing the code to the matlab path:

    cbrewer_folder = [ pwd '\cbrewer']; % pwd gets the path to the current folder.addpath(cbrewer_folder);

    Warning: Name is nonexistent or not a directory: C:\Users\laduran\Desktop\research\presentations\2016_06_07 Figure making\cbrewer.

    If we call the cbrewer command, it will display the available colormaps:

    cbrewer;

    [colormap] = cbrewer(ctype, cname, ncol [, interp_method]) INPUT: - ctype: type of color table *seq* (sequential), *div* (divergent), *qual* (qualitative) - cname: name of colortable. It changes depending on ctype. - ncol: number of color in the table. It changes according to ctype and cname - interp_method: interpolation method (see interp1.m). Default is "cubic" ) Sequential tables:

    http://colorbrewer2.org/https://www.mathworks.com/matlabcentral/fileexchange/34087-cbrewer---colorbrewer-schemes-for-matlabhttps://www.mathworks.com/matlabcentral/fileexchange/34087-cbrewer---colorbrewer-schemes-for-matlab

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    'Blues' 'BuGn' 'BuPu' 'GnBu' 'Greens' 'Greys' 'Oranges' 'OrRd' 'PuBu' 'PuBuGn' 'PuRd' 'Purples' 'RdPu' 'Reds' 'YlGn' 'YlGnBu' 'YlOrBr' 'YlOrRd' 'Spectral'

    Divergent tables: 'BrBG' 'PiYG' 'PRGn' 'PuOr' 'RdBu' 'RdGy' 'RdYlBu' 'RdYlGn'

    Qualitative tables: 'Accent' 'Dark2' 'Paired' 'Pastel1' 'Pastel2' 'Set1' 'Set2' 'Set3'

    Cbrewer provides three types of colormaps. Divergent and Sequential colormaps are better todisplay the continuous change in a quantity. In contrast, the Qualitative colormaps areintended to provide colors to separate data into groups. Below, I compare the defaultMATLAB colormap (called Jet) with one of the diverging colormaps available from thecbrewer function (called Spectral):

    fh = figure;

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    set(fh,'color','w');contourf(peaks);title('Default MATLAB colormap (Jet)','fontsize',13);colorbar;

    fh = figure;set(fh,'color','w');contourf(peaks)cmap = cbrewer('div','Spectral',40);colormap(cmap);title('Cbrewer divergent colormap (Spectral)','fontsize',13);colorbar;

    The Jet colormap is made of strong, saturated colors. Saturated colors are easy to see, butmay overwhelm the reader. A colormap with less saturated colors, like the Spectral colormap

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    above, still allows to differentiate levels without taxing the reader's visual system so much.

    Choosing colors. Option III: Creating your own colormaps.

    Alternatively, you can create a custom colormap. Bang Wong, talking about color coding inhis column Points of View, suggest a simple way for creating qualitative colormaps using theHue/Saturation/Lightness colorspace (HSL). Below is an excerpt from the column,describing HSL:

    Every color is described by three properties: hue, saturation and lightness. Hue is theattribute we use to classify a color as red or yellow. Saturation describes the neutrality of acolor; a red object with little or no white is said to be very saturated. The lightness of a colortells us about its relative ordering on the dark-to-light scale

    (Excerpt from http://www.nature.com/nmeth/journal/v7/n8/full/nmeth0810-573.html)

    Below, I create a set of Qualitative colormaps by creating colors in the HSV colorspace (verysimilar to HSL) and then converting the colors back to RGB.

    figure('color','w'); hold on;

    cmapNum = 10; % Numbers of colormaps to create.colorNum = 10; % Number of colors per colormap.

    rgb_color = zeros(colorNum,3,cmapNum);

    for jj = 1:cmapNum

    % Define vectors where we simultaneously change Hue,Saturation and Brightness.

    Brightness = 0.95:-(0.95-0.5)/colorNum:0.5; % From 0.5 to 0.95. Saturation = 0.1:(0.9-0.1)/colorNum:.9; % From 0.1 to 0.9. Hue = 0:1/colorNum:1; % From 0.1 to 1.0.

    for ii = 1:colorNum

    % Define a color in the hsv scale and convert to rgb.

    rgb_color(ii,:,jj) = hsv2rgb([ mod(Hue(ii) + jj/cmapNum,1) Saturation(ii) Brightness(ii) ]); % Hue Saturation Value/Brightness.

    plot(ii,2*jj,'s','markerfacecolor',squeeze(rgb_color(ii,:,jj)),... % Squeeze remove unnecesary dimensions of an array. 'markeredgecolor','none',... 'markersize',20); end

    end

    axis equal;xlim([0 colorNum*1.1]);ylim([0 2*cmapNum]);set(gca,'Xtick',[],'Ytick',[],'XColor',[1 1 1],'YColor',[1 1 1]);xlabel(['Decreasing Brightness (Value)' sprintf('\n') ... 'Changing Hue' sprintf('\n') 'Increasing Saturation'],'color','k');annotation('textarrow',[.33 .7],[0.15 0.15]);

    http://www.nature.com/nmeth/journal/v7/n8/full/nmeth0810-573.html

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Above we changed the color of the axis to white instead of using 'axis off', because the latterwould have deleted also the X label. We also used a nifty annotation function to create anarrow. We can now test whether the colormap is able to differentiate datasets in a plot:

    figure('color','w'); hold on;

    cmap_idx = 5; % Choose one of the colormaps.

    for ii = 1:colorNum

    % Create ColorNum random datasets, with 20 elements each. theta1 = 2*pi*rand(20,1); % Generate 20 random angles between 0 and 2*pi. radius1 = rand(20,1); % Generate 20 random radii between 0 and 1. x1 = radius1.*cos(theta1); % Transform to cartesian coordinates. y1 = radius1.*sin(theta1);

    theta2 = 2*pi*rand(1); % Generate 20 random angles between 0 and 2*pi. radius2 = 5*rand(1); % Generate 20 random radii between 0 and 5. x2 = radius2.*cos(theta2); % Transform to cartesian coordinates. y2 = radius2.*sin(theta2);

    x = x1+x2; % Generate data inside an unity circle that is inside a circle of radius 5. y = y1+y2;

    plot(x,y,'o','markerfacecolor',squeeze(rgb_color(ii,:,cmap_idx)),... 'markeredgecolor','none',... 'markersize',8);end

    axis equal;xlim([-5 5]);ylim([-5 5]);box on;set(gca,'Xtick',[-5 0 5],'XTickLabel',{'-5','0','5'},... 'Ytick',[-5 0 5],'YTickLabel',{'-5','0','5'});title('Qualitative colormap, {\itala} Bang Wong');

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Displaying multiple datasets on a plot.

    Above I showed a single colormap example. But many times, when we analyze scientificdata, it is useful to show multiple plots in a figure, to help us compare different data sets.MATLAB® has a simple function, called subplot, that allows us to allocate multiple plotsinto one figure. Below, I show all the posible colormaps created in above in an array of 3x3plots:

    figure('color','w'); hold on;

    for jj = 1:9 % For each colormap.

    subplot(3,3,jj); hold on;

    for ii = 1:colorNum

    % Create ColorNum random datasets, with 20 elements each. theta1 = 2*pi*rand(20,1); % Generate 20 random angles between 0 and 2*pi. radius1 = rand(20,1); % Generate 20 random radii between 0 and 1. x1 = radius1.*cos(theta1); % Transform to cartesian coordinates. y1 = radius1.*sin(theta1);

    theta2 = 2*pi*rand(1); % Generate 20 random angles between 0 and 2*pi. radius2 = 5*rand(1); % Generate 20 random radii between 0 and 5. x2 = radius2.*cos(theta2); % Transform to cartesian coordinates. y2 = radius2.*sin(theta2);

    x = x1+x2; % Generate data inside an unity circle that is inside a circle of radius 5. y = y1+y2;

    plot(x,y,'o','markerfacecolor',squeeze(rgb_color(ii,:,jj)),... 'markeredgecolor','none',... 'markersize',5); end

    axis equal; xlim([-5 5]); ylim([-5 5]); box on; xlabel('X'); ylabel('Y'); set(gca,'Xtick',[-5 0 5],'XTickLabel',{'-5','0','5'},... 'Ytick',[-5 0 5],'YTickLabel',{'-5','0','5'});end

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    To visualize the plots better, you can increase the size of the figure:

    figure('color','w','units','inches','position',[.2 .5 9 9]); hold on;

    for jj = 1:9 % For each colormap.

    subplot(3,3,jj); hold on;

    for ii = 1:colorNum

    % Create ColorNum random datasets, with 20 elements each. theta1 = 2*pi*rand(20,1); % Generate 20 random angles between 0 and 2*pi. radius1 = rand(20,1); % Generate 20 random radii between 0 and 1. x1 = radius1.*cos(theta1); % Transform to cartesian coordinates. y1 = radius1.*sin(theta1);

    theta2 = 2*pi*rand(1); % Generate 20 random angles between 0 and 2*pi. radius2 = 5*rand(1); % Generate 20 random radii between 0 and 5. x2 = radius2.*cos(theta2); % Transform to cartesian coordinates. y2 = radius2.*sin(theta2);

    x = x1+x2; % generate data inside an unity circle that is inside a circle of radius 5. y = y1+y2;

    plot(x,y,'o','markerfacecolor',squeeze(rgb_color(ii,:,jj)),... 'markeredgecolor','none',... 'markersize',8); end

    axis equal; xlim([-5 5]); ylim([-5 5]); box on; xlabel('X'); ylabel('Y'); set(gca,'Xtick',[-5 0 5],'XTickLabel',{'-5','0','5'},... 'Ytick',[-5 0 5],'YTickLabel',{'-5','0','5'});

    end

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Below, is an example where I create 100 different colormaps, and display then in a 10x10subplot array, using a scatter plot of random data as done above:

    figure('color','w','units','inches','position',[.2 .5 9 9]); hold on;

    cmapNum = 100; % Numbers of colormaps to create.colorNum = 10; % Number of colors per colormap.

    for jj = 1:cmapNum

    % Define vectors where we simultaneously change Hue,Saturation and Brightness.

    Brightness = 0.95:-(0.95-0.5)/colorNum:0.5; % From 0.3 to 0.95. Saturation = 0.1:(0.9-0.1)/colorNum:.9; % From 0.1 to 0.9.

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Hue = 0:1/colorNum:1; % From 0.1 to 1.0.

    subplot(10,10,jj); hold on;

    for ii = 1:colorNum

    % Define a color in the hsv scale and convert to rgb. rgb_color = hsv2rgb([ mod(Hue(ii) + jj/cmapNum,1) Saturation(ii) Brightness(ii) ]); % Hue Saturation Value/Brightness.

    % Create ColorNum random datasets, with 20 elements each. theta1 = 2*pi*rand(20,1); % Generate 20 random angles between 0 and 2*pi. radius1 = rand(20,1); % Generate 20 random radii between 0 and 1. x1 = radius1.*cos(theta1); % Transform to cartesian coordinates. y1 = radius1.*sin(theta1);

    theta2 = 2*pi*rand(1); % Generate 20 random angles between 0 and 2*pi. radius2 = 5*rand(1); % Generate 20 random radii between 0 and 5. x2 = radius2.*cos(theta2); % Transform to cartesian coordinates. y2 = radius2.*sin(theta2);

    x = x1+x2; % generate data inside an unity circle that is inside a circle of radius 5. y = y1+y2;

    plot(x,y,'o','markerfacecolor',rgb_color,... 'markeredgecolor','none',... 'markersize',5); end

    axis equal; xlim([-5 5]); ylim([-5 5]); box on;

    % Only display Xlabels, Ylabels and ticks in plots located at the bottom and the left of the figure.

    fontsize = 10; if mod(jj,10) == 1 && jj ~= 91 set(gca,'Xtick',[],... 'Ytick',[-5 0 5],'YTickLabel',{'-5','0','5'},... 'fontsize',fontsize); ylabel('Y'); elseif jj == 91 set(gca,'Xtick',[-5 0 5],'XTickLabel',{'-5','0','5'},... 'Ytick',[-5 0 5],'YTickLabel',{'-5','0','5'},... 'fontsize',fontsize); ylabel('Y'); xlabel('X'); elseif jj > 91 set(gca,'Xtick',[-5 0 5],'XTickLabel',{'-5','0','5'},... 'Ytick',[],... 'fontsize',fontsize); xlabel('X'); else set(gca,'Xtick',[],... 'Ytick',[],... 'fontsize',fontsize); end

    end

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    Above, in addition to show multiple plots, we only show the ticks and labels of subplots atthe bottom and left of the subplot array, to save some space, and in this way make more roomfor the figures. However, that only partially helps. To have a greater control of the apperanceof subplots, one can use the subaxis function instead. The first thing to do is to downloadsubaxis from the MATLAB Exchange, and add the function to the MATLAB path:

    subaxis_folder = [pwd '\subaxis']; % pwd gets the path to the current folder.addpath(subaxis_folder);

    Warning: Name is nonexistent or not a directory: C:\Users\laduran\Desktop\research\presentations\2016_06_07 Figure making\subaxis.

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    subaxis gives you more flexibility to adjust the appearence of subplots, by defining, forexample, the horizontal and vertical distance separating the plots, as well as the size of theright, left, bottom and top margins from the figure:

    figure('color','w','units','inches','position',[.2 .5 9 9]); hold on;

    % Subaxis parameters.SH = 'SpacingHoriz'; SHv = 0.01; % Horizontal spacing between the subplots.SV = 'SpacingVert'; SVv = 0.01; % Vertical spacing between the subplots.MR = 'MarginRight'; MRv = 0.05; % Size of the margin at the right side of the figure.ML = 'MarginLeft'; MLv = 0.05; % Size of the margin at the left side of the figure.MT = 'MarginTop'; MTv = 0.05; % Size of the margin at the Top of the figure.MB = 'MarginBottom'; MBv = 0.05; % Size of the margin at the Bottom of the figure.

    cmapNum = 100; % Numbers of colormaps to create.colorNum = 10; % Number of colors per colormap.

    for jj = 1:cmapNum

    % Define vectors where we simultaneously change Hue, Saturation and Brightness.

    Brightness = 0.95:-(0.95-0.5)/colorNum:0.5; % From 0.5 to 0.95. Saturation = 0.1:(0.9-0.1)/colorNum:.9; % From 0.1 to 0.9. Hue = 0:1/colorNum:1; % From 0.1 to 1.0.

    subaxis(10,10,jj,SH,SHv,SV,SVv,MR,MRv,ML,MLv,MT,MTv,MB,MBv); hold on;

    for ii = 1:colorNum

    % Define a color in the hsv scale and convert to rgb. rgb_color = hsv2rgb([ mod(Hue(ii) + jj/cmapNum,1) Saturation(ii) Brightness(ii) ]); % Hue Saturation Value/Brightness.

    % Create ColorNum random datasets, with 20 elements each. theta1 = 2*pi*rand(20,1); % Generate 20 random angles between 0 and 2*pi. radius1 = rand(20,1); % Generate 20 random radii between 0 and 1. x1 = radius1.*cos(theta1); % Transform to cartesian coordinates. y1 = radius1.*sin(theta1);

    theta2 = 2*pi*rand(1); % Generate 20 random angles between 0 and 2*pi. radius2 = 5*rand(1); % Generate 20 random radii between 0 and 5. x2 = radius2.*cos(theta2); % Transform to cartesian coordinates. y2 = radius2.*sin(theta2);

    x = x1+x2; % Generate data inside an unity circle that is inside a circle of radius 5. y = y1+y2;

    plot(x,y,'o','markerfacecolor',rgb_color,... 'markeredgecolor','none',... 'markersize',5); end

    axis equal; xlim([-5.2 5.2]); ylim([-5.2 5.2]); box on;

    % Only display Xlabels, Ylabels and ticks in plots located at the bottom and the left of the figure.

    fontsize = 9; if mod(jj,10) == 1 && jj ~= 91 set(gca,'Xtick',[],... 'Ytick',[-5 0 5],'YTickLabel',{'-5','0','5'},... 'fontsize',fontsize); ylabel('Y'); elseif jj == 91 set(gca,'Xtick',[-5 0 5],'XTickLabel',{'-5','0','5'},... 'Ytick',[-5 0 5],'YTickLabel',{'-5','0','5'},... 'fontsize',fontsize); ylabel('Y'); xlabel('X'); elseif jj > 91 set(gca,'Xtick',[-5 0 5],'XTickLabel',{'-5','0','5'},... 'Ytick',[],... 'fontsize',fontsize); xlabel('X'); else set(gca,'Xtick',[],... 'Ytick',[],... 'fontsize',fontsize); end

    end

  • Basic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab

    Figure_guide_LS_2016.htm[1/18/2017 11:13:17 AM]

    by Leonardo A. Sepulveda. Last version: 06/15/2015

    Published with MATLAB® 7.13

    Local DiskBasic tips for creating visually appealing graphics in MATLAB®, from the Golding Lab