[plotting] object way of editing plot properties

This commit is contained in:
Jan Grewe 2019-11-28 16:56:26 +01:00
parent 2e0b2a5239
commit 19983392c5
6 changed files with 152 additions and 95 deletions

View File

@ -1,10 +1,12 @@
time = 0.0:0.001:1.0; time = 0.0:0.001:1.0;
y = sin(2 * pi * 2 .* time); y = sin(2 * pi * 2 .* time);
figure
hold on hold on
set(gcf, 'Color', 'white', 'PaperUnit', 'centimeters', 'PaperSize', [4 4], ... fig = figure();
'PaperPosition', [0 0 4 4]) fig.PaperUnits = 'centimeters';
fig.PaperSize = [4 4];
fig.PaperPosition = [0.0 0.0 4, 4];
fig.Color = 'white';
plot(time, y) plot(time, y)
plot([0.0 1.0], [0.0 0.0], '--', 'color','k', 'linewidth', 0.75) plot([0.0 1.0], [0.0 0.0], '--', 'color','k', 'linewidth', 0.75)

View File

@ -1,26 +1,40 @@
load('pyramidal_response.mat') load('pyramidal_response.mat')
threshold = 20; % mV threshold = 20; % mV
hold on hold on;
plot(time*1000.0, neuronal_data, 'color', [0.2 0.5 0.7], ... plot(time*1000.0, neuronal_data, 'color', [0.2 0.5 0.7], ...
'linewidth', 1., 'displayname', 'Membrane voltage') 'linewidth', 1., 'displayname', 'Membrane voltage');
plot(spikes*1000.0, ones(size(spikes)) .* threshold, 'r.', ... plot(spikes*1000.0, ones(size(spikes)) .* threshold, 'r.', ...
'markersize', 15, 'displayname', 'Spike times') 'markersize', 15, 'displayname', 'Spike times');
line([time(1) time(end)], [threshold threshold], 'linestyle', '--', ... line([time(1) time(end)], [threshold threshold], 'linestyle', '--', ...
'linewidth', 0.75, 'color', [0.5 0.5 0.5], 'displayname', 'Threshold') 'linewidth', 0.75, 'color', [0.5 0.5 0.5], 'displayname', 'Threshold');
xlabel('Time [ms]', 'fontname', 'times', 'fontsize', 11) axes = gca();
ylabel('Potential [mV]', 'fontname', 'times', 'fontsize', 11) axes.XLabel = 'Time [ms]';
title('ELL pyramidal neuron', 'fontname', 'times', 'fontsize', 12) axes.YLabel = 'Potential [mV]';
ylim([0 40]) axes.Title = 'ELL pyramidal neuron';
xlim([500 1700]) axes.XLim = [[500 1700];
box('off') axes.YLim = [0 40];
l = legend(gca,'show'); axes.XMinorTick = 'on';
set(l,'location','northeast', 'fontsize', 11, 'linewidth', 1.); axes.YMinorTick = 'on';
set(gca, 'xminortick','on','yminortick','on') axes.TickDir = 'out';
set(gca, 'tickdir','out', 'linewidth', 1.5, 'fontname', 'times', ... axes.LineWidth = 1.5;
'fontsize', 11) axes.box('off')
set(gcf, 'paperunits', 'centimeters', 'papersize', [15 7]);
set(gcf, 'paperposition',[0.0 0.0 15, 7], 'color', 'white')
saveas(gcf, 'spike_detection.pdf', 'pdf') axes.FontName = 'Times';
axes.FontSize = 8;
axes.TitleFontSizeMultiplier = 1.5;
axes.LabelFontSizeMultiplier = 1.25;
l = legend(axes, 'show');
l.Location = "northeast";
l.FontSize = 11;
l.LineWidth = 1;
fig = gcf();
fig.PaperUnits = 'centimeters';
fig.PaperSize = [15, 7];
fig.PaperPosition = [0.0 0.0 15, 7];
fig.Color = 'white';
saveas(gcf, 'spike_detection.pdf', 'pdf')

View File

@ -11,8 +11,11 @@ err_upper_asym = prctile(asym_data, 75, 1);
err_lower_asym = prctile(asym_data, 25, 1); err_lower_asym = prctile(asym_data, 25, 1);
fig = figure(); fig = figure();
set(fig, 'paperunits', 'centimeters', 'papersize', [15 6.5], ... fig.PaperUnits = 'centimeters';
'paperposition', [0.0 0.0 15, 6.5], 'color', 'white') fig.PaperSize = [15 6.5];
fig.PaperPosition = [0.0 0.0 15, 6.5];
fig.Color = 'white';
subplot(1,3,1) subplot(1,3,1)
errorbar(x_data, avg_sym, err_sym, 'marker', 'o') errorbar(x_data, avg_sym, err_sym, 'marker', 'o')
xlim([-.5, 6.5]) xlim([-.5, 6.5])

View File

@ -7,9 +7,11 @@ f_y = 1.5;
dt = 2*pi/500; dt = 2*pi/500;
f = figure(); f = figure();
set(f, 'visible', 'off'); f.Visible = false;
set(f, 'PaperUnits', 'centimeter', 'PaperSize', [2.5, 2.5], ... f.PaperUnits = 'centimeters';
'PaperPosition', [0, 0, 2.5, 2.5], 'Color', 'white') f.PaperSize = [2.5 2.5];
f.PaperPosition = [0.0 0.0 2.5, 2.5];
f.Color = 'white';
writer = VideoWriter('../lecture/images/lissajous.mp4', 'MPEG-4'); writer = VideoWriter('../lecture/images/lissajous.mp4', 'MPEG-4');
writer.FrameRate = 25; writer.FrameRate = 25;
@ -40,8 +42,10 @@ for i = 1:max_frames
end end
f = figure(); f = figure();
set(f, 'PaperUnits', 'centimeter', 'PaperSize', [5, 5], ... f.PaperUnits = 'centimeters';
'PaperPosition', [0, 0, 5, 5], 'Color', 'white') f.PaperSize = [2.5 2.5];
f.PaperPosition = [0.0 0.0 2.5, 2.5];
f.Color = 'white';
scatter(x_positions, y_positions, 10, 'r', 'filled'); scatter(x_positions, y_positions, 10, 'r', 'filled');
xlim([-1.05, 1.05]) xlim([-1.05, 1.05])
@ -51,4 +55,4 @@ yticks([-1., 0., 1.])
xlabel('x') xlabel('x')
ylabel('y') ylabel('y')
saveas(f, '../lecture/images/lissajous.png') saveas(f, '../lecture/images/lissajous.png')

View File

@ -1,5 +1,5 @@
frequency = 5; % frequency of the sine wave in Hz frequency = 5; % frequency of the sine wave in Hz
time = 0.01:0.01:1.0; % the time axis time = 0.01:0.01:1.0; % the time axis in seconds
signal = sin(2 * pi * time * frequency); signal = sin(2 * pi * time * frequency);
plot(time, signal); plot(time, signal);

View File

@ -3,7 +3,7 @@
We may count the ability of adequately presenting scientific data to We may count the ability of adequately presenting scientific data to
the core competences needed to do science. We need to present data in the core competences needed to do science. We need to present data in
a meaningful way that supports understanding of the data and the a meaningful way that supports understanding of the data and the
results. results without biases.
\begin{figure}[hb!] \begin{figure}[hb!]
\includegraphics[width=0.9\columnwidth]{convincing} \includegraphics[width=0.9\columnwidth]{convincing}
@ -15,13 +15,13 @@ results.
Plotting data in \matlab{} is rather straight forward for simple line Plotting data in \matlab{} is rather straight forward for simple line
plots. By calling \code[plot()]{plot(x, y)} a simple line plot will be plots. By calling \code[plot()]{plot(x, y)} a simple line plot will be
created. This figure, however is missing any annotations like axis created. The resulting figure, however is missing any annotations like axis
labeling, a legend, etc.. There are two options to edit the plot: (i) labeling, a legend, etc.. There are two options to edit the plot: (i)
the graphical user interface (GUI) or the command line. Both ways have the graphical user interface (GUI) or the command line. Both ways have
their right to exist associated with respective pros and cons. The UI their right to exist associated with respective pros and cons. The UI
way of editing plots is ideal for experimenting the command line way of editing plots is ideal for experimenting, the command line
approach is best suited for automation and to achieve a consistent approach is best suited for automation and to achieve a consistent
layout across figures and graphs. layout across figures and graphs in a paper or thesis.
\begin{figure} \begin{figure}
\begin{minipage}[t]{0.6\textwidth} \begin{minipage}[t]{0.6\textwidth}
@ -95,31 +95,35 @@ number of datasets.
Creating a simple line-plot is rather easy. Assuming there exists a Creating a simple line-plot is rather easy. Assuming there exists a
variable \varcode{y} in the \codeterm{Workspace} that contains the variable \varcode{y} in the \codeterm{Workspace} that contains the
measurement data it is enough to call \code[plot()]{plot(y)}. At the measurement data it is enough to call \code[plot()]{plot(y)}. At the
first call of this function a new window will be opened and the data first call of this function a new \codeterm{figure} will be opened and
will be plotted with as a line plot. If you repeatedly call this the data will be plotted with as a line plot. If you repeatedly call
function the current plot will be replaced unless the \code[hold]{hold this function the current plot will be replaced unless the
on} command was issued before. If it was, the current plot is held \code[hold]{hold on} command was issued before. If it was, the current
and a second line will be added to it. Calling \code[hold]{hold off} plot is held and a second line will be added to it. Calling
will release the plot and any subsequent plotting will replace the \code[hold]{hold off} will release the plot and any subsequent
previous plot. plotting will replace the previous plot.
In our previous call to \varcode{plot} we have provided just a single In our previous call to \varcode{plot} we provided just a single
variable containing the y-values of the plot. The x-axis will be variable containing the y-values of the plot. The x-axis will be
scaled from zero to the number of elements in \varcode{y} the x-values scaled from zero to the number of elements in \varcode{y} the x-values
are automatically substituted assuming a constant stepsize of 1. This are automatically substituted assuming a constant stepsize of 1. This
automatic scaling is probably not desired and thus, we need to provide automatic scaling is probably not desired and thus, we need to provide
the missing information ourselves. The respective call will expand to the missing information ourselves. Thus, we need a second variable
\code[plot()]{plot(x, y)}. In axis will be scaled from the minimum in that contains the respective \varcode{x} values. The length of
\varcode{x} to the maximum of \varcode{x} and by default it will be \varcode{x} and \varcode{y} must be the same otherwise the later call
plotted as a line plot with a solid blue line of the with 1pt. A of the \varcode{plot} function will raise an error. The respective
second plot that is added to the figure will be plotted in red using call will expand to \code[plot()]{plot(x, y)}. The x-axis will be now
the same standard settings. The order of the used colors depends on be scaled from the minimum in \varcode{x} to the maximum of
the \enterm{colormap} settings which can be adjusted to personal taste \varcode{x} and by default it will be plotted as a line plot with a
or need. Table\,\ref{plotlinestyles} shows some predefined values that solid blue line of the linewidth 1pt. A second plot that is added to the
figure will be plotted in red using the same settings. The
order of the used colors depends on the \enterm{colormap} settings
which can be adjusted to personal taste or
need. Table\,\ref{plotlinestyles} shows some predefined values that
can be chosen for the line style, the marker, or the color. For can be chosen for the line style, the marker, or the color. For
additional options consult the help. additional options consult the help.
\begin{table}[tp] \begin{table}[htp]
\titlecaption{Predefined line styles (left), colors (center) and \titlecaption{Predefined line styles (left), colors (center) and
marker symbols (right).}{}\label{plotlinestyles} marker symbols (right).}{}\label{plotlinestyles}
\begin{tabular}[t]{lc} \hline \begin{tabular}[t]{lc} \hline
@ -173,33 +177,29 @@ chosen.
not distinguish between red and green. not distinguish between red and green.
\item Can you distinguish the colors in a b/w respectively gray \item Can you distinguish the colors in a b/w respectively gray
scale print? scale print?
\item Color figures in publications often cost extra money. \item Color figures in publications sometimes cost extra money.
\end{itemize} \end{itemize}
\end{important} \end{important}
\subsection{Changing the axis properties} \subsection{Changing the axes properties}
The first thing a data plot needs are axis labels with a correct The first thing a plot needs are axis labels with correct units. By
unit. By calling the functions \code[xlabel]{xlabel('Time [ms]')} and calling the functions \code[xlabel]{xlabel('Time [ms]')} and
\code[ylabel]{ylabel{'Voltage [mV]'}} these can be set. By default the \code[ylabel]{ylabel('Voltage [mV]')} these can be set. By default the
axes will be scaled to show the whole data range. The extremes will be axes will be scaled to show the full extent of the data. The extremes
selected as the closest integer for small values or the next full will be selected as the closest integer for small values or the next
multiple of tens, hundreds, thousands, etc.\ depending on the maximum full multiple of tens, hundreds, thousands, etc.\ depending on the
value. If these defaults do not match our needs, the limits of the maximum value. If these defaults do not match your needs, the limits
axes can be explicitly set with the functions \code[xlim()]{xlim()} of the axes can be explicitly set with the functions
and \code[ylim()]{ylim()}. To do this, the functions expect a single \code[xlim()]{xlim()} and \code[ylim()]{ylim()}. To do this, the
argument, that is a vector containing the minimum and maximum functions expect a single argument, that is a 2-element vector
value. Table\,\ref{plotaxisprops} lists some of the commonly adjusted containing the minimum and maximum value. Table\,\ref{plotaxisprops}
properties of an axis. These properties can be set using the lists some of the commonly adjusted properties of an axis. To set
\code[set()]{set()} function. The \code{set} function expects as a these properties, we need to have the axes object which can either be
first argument a \enterm{handle} of the affected axis. An axis handle stored in a variable when calling \varcode{plot} (\code{axes =
of the current plot is returned by the \code[gca]{gca} function (gca plot(x,y);}) or can be retrieved using the \code[gca]{gca} function
stands for ``get current axis''). The following arguments passed to (gca stands for ``get current axes''). Changing the properties of the axes
\code{set} are pairs of the property name and the desired value. It is object will update the plot (listing\,\ref{niceplotlisting}).
possible to set any number of properties using a single call to
\code{set}. See listing\,\ref{niceplotlisting} (lines 20 and 21) for
an example (these commands could be joined into a single call to
\code{set} but have been split for better readability).
\begin{table}[tp] \begin{table}[tp]
\titlecaption{Incomplete list of axis properties.}{For a complete \titlecaption{Incomplete list of axis properties.}{For a complete
@ -247,27 +247,30 @@ an example (these commands could be joined into a single call to
\end{tabular*} \end{tabular*}
\end{table} \end{table}
Like axes, also figure has several properties that can be adjusted to Like the axes, also the figure has several properties that can be
the current needs. Most notably the paper (figure) size and the adjusted to the current needs. Most notably the paper (figure) size
placement of the axes on the paper. Table\,\ref{plotfigureprops} lists and the placement of the axes on the
commonly used properties. For a complete reference check the help. To paper. Table\,\ref{plotfigureprops} lists commonly used
change the properties, we again use the \code{set()} function. The properties. For a complete reference check the help. To change the
first argument is now a handle to the current figure, not the current figure's appearance, we need to change the properties of the figure
axis as before. Analogously to the \code{gca} command there is a object which can be retrieved during creation of the figure (\code{fig
\code{gcf} (``get current figure'') command with which the handle can = figure();}) or by using the \code{gcf} (``get current figure'')
be retrieved. command.
The script shown in the listing\,\ref{niceplotlisting} exemplifies The script shown in the listing\,\ref{niceplotlisting} exemplifies
several features of the plotting system and automatically generates several features of the plotting system and automatically generates
and saves figure\,\ref{spikedetectionfig}. With any execution of this and saves figure\,\ref{spikedetectionfig}. With any execution of this
script exactly the same plot will be created. If we decided to plot a script exactly the same plot will be created. If we decided to plot a
different recording, the format will stay exactly the same, just the different recording, the format will stay exactly the same, just the
data changes. Of special interest are the lines 22 and 23 which set data changes. Of special interest are the lines 35 through 37 which
the size of the figure and positions the axes on the paper. Line 26 set the size of the figure and positions the axes on the paper. Lines
finally saves the figure in the 'pdf' format to file. When calling the 24 through 27 control the font used for labeling inside the axes. The
function \code{saveas()} the first argument is the current figure axes holds the default \varcode{FontSize} and via multipliers applied
handle, the second the file name, and the last one defines the to the default one can control the size of the title (line 26) or the
output format (box\,\ref{graphicsformatbox}). axes labels (line 27). Line 40 finally saves the figure in the 'pdf'
format to file. When calling the function \code{saveas()} the first
argument is the current figure handle, the second the file name, and
the last one defines the output format (box\,\ref{graphicsformatbox}).
\begin{figure}[t] \begin{figure}[t]
\includegraphics{spike_detection} \titlecaption{Automatically \includegraphics{spike_detection} \titlecaption{Automatically
@ -325,6 +328,37 @@ output format (box\,\ref{graphicsformatbox}).
label=niceplotlisting]{automatic_plot.m} label=niceplotlisting]{automatic_plot.m}
\begin{ibox}[t]{\label{handlevsobjectbox}The wind of change.}
The way figure or axis properties can be adapted has been changed
with recent \matlab{} versions. In versions before \emph{R2014b}
properties could be read and set using the functions
\code[get()]{get} and \code[set()]{set}. The first argument these
functions expect are valid figure or axis \emph{handles} which were
returned by the \code{figure} and \code{plot} functions, or could be
retrieved using \code[gcf()]{gcf} or \code[gca()]{gca} for the
current figure or axis handle, respectively. Subsequent arguments
passed to \code{set} are pairs of a property's name and the desired
value.
\begin{lstlisting}[caption={Using set to change figure and axis properties.}]
frequency = 5; % frequency of the sine wave in Hz
time = 0.01:0.01:1.0; % the time axis in seconds
signal = sin(2 * pi * time * frequency);
plot(time, signal)
axes_handle = gca(); % get current axes
figure_handle = gcf(); % get current figure
set(axes_handle, 'XLabel', 'time [s]', 'YLabel', 'amplitude');
set(figure_handle, 'PaperSize', [5.5, 5.5], 'PaperUnit', 'centimeters', ...
'PaperPosition', [0, 0, 5.5, 5.5]);
\end{lstlisting}
With newer versions the handles returned by \varcode{gcf} and
\varcode{gca} are ``objects'' and setting properties became much
easier as it is used throughout this chapter. For downward
compatibility with older versions set and get still work in current
versions of \matlab{}.
\end{ibox}
\section{Plot examples} \section{Plot examples}
So far we have introduced the standard line plots. Next to these there So far we have introduced the standard line plots. Next to these there
@ -485,7 +519,7 @@ its properties. See the \matlab{} help for more information.
\lstinputlisting[caption={Illustrating estimation errors using error bars. Script that \lstinputlisting[caption={Illustrating estimation errors using error bars. Script that
creates \figref{errorbarplot}. A, B}, creates \figref{errorbarplot}. A, B},
label=errorbarlisting, firstline=13, lastline=29, label=errorbarlisting, firstline=13, lastline=31,
basicstyle=\ttfamily\scriptsize]{errorbarplot.m} basicstyle=\ttfamily\scriptsize]{errorbarplot.m}
\subsubsection{Fill} \subsubsection{Fill}
@ -507,7 +541,7 @@ version of the x-values to the original x-values using \code{cat} and
\code{fliplr} for concatenation and inversion, respectively (line 3 in \code{fliplr} for concatenation and inversion, respectively (line 3 in
listing \ref{errorbarlisting2}; Depending on the layout of your data listing \ref{errorbarlisting2}; Depending on the layout of your data
you may need concatenate along a different dimension of the data and you may need concatenate along a different dimension of the data and
use \code{flipud} instead). The y-coordinates of the polygon vertices use \code{flipud} instead). The y-coordinates of the polygon vertices
are concatenated in a similar way (line 4). In the example shown here are concatenated in a similar way (line 4). In the example shown here
we accept the polygon object that is returned by fill (variable p) and we accept the polygon object that is returned by fill (variable p) and
use it to change a few properties of the polygon. The \emph{FaceAlpha} use it to change a few properties of the polygon. The \emph{FaceAlpha}
@ -519,7 +553,7 @@ connecting the average values (line 12).
\lstinputlisting[caption={Illustrating estimation errors using a shaded area. Script that \lstinputlisting[caption={Illustrating estimation errors using a shaded area. Script that
creates \figref{errorbarplot} C.}, label=errorbarlisting2, creates \figref{errorbarplot} C.}, label=errorbarlisting2,
firstline=30, firstline=33,
basicstyle=\ttfamily\scriptsize]{errorbarplot.m} basicstyle=\ttfamily\scriptsize]{errorbarplot.m}
\subsection{Annotations, text} \subsection{Annotations, text}
@ -600,7 +634,7 @@ Lissajous figure. The basic steps are:
\end{enumerate} \end{enumerate}
\lstinputlisting[caption={Making animations and saving them as a \lstinputlisting[caption={Making animations and saving them as a
movie.}, label=animationlisting, firstline=3, lastline=33, movie.}, label=animationlisting, firstline=16, lastline=36,
basicstyle=\ttfamily\scriptsize]{movie_example.m} basicstyle=\ttfamily\scriptsize]{movie_example.m}
\section{What makes a good plot?} \section{What makes a good plot?}