<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Handle graphics &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/handle-graphics/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Thu, 07 Nov 2019 13:43:36 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Improving graphics interactivity</title>
		<link>https://undocumentedmatlab.com/articles/improving-graphics-interactivity?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=improving-graphics-interactivity</link>
					<comments>https://undocumentedmatlab.com/articles/improving-graphics-interactivity#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 21 Apr 2019 21:03:10 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Toolbar]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8723</guid>

					<description><![CDATA[<p>Matlab R2018b added default axes mouse interactivity at the expense of performance. Luckily, we can speed-up the default axes. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity">Improving graphics interactivity</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events" rel="bookmark" title="Undocumented HG2 graphics events">Undocumented HG2 graphics events </a> <small>Matlab's new HG2 graphics engine includes many new undocumented events that could be used in various ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-save-performance" rel="bookmark" title="Improving save performance">Improving save performance </a> <small>There are many different ways of improving Matlab's standard save function performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Matlab release R2018b added the concept of <a href="https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar" target="_blank">axes-specific toolbars</a> and default <a href="https://www.mathworks.com/help/matlab/creating_plots/control-axes-interactions.html" rel="nofollow" target="_blank">axes mouse interactivity</a>. <span class="alignright"><img decoding="async" src="https://undocumentedmatlab.com/images/speedometer4d_200x200.gif" alt="Accelerating MATLAB Performance" title="Accelerating MATLAB Performance" width="200" height="200" /></span> Plain 2D plot axes have the following default interactions enabled by default: <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.paninteraction.html" rel="nofollow" target="_blank">PanInteraction</a>, <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.zoominteraction.html" rel="nofollow" target="_blank">ZoomInteraction</a>, <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.datatipinteraction.html" rel="nofollow" target="_blank">DataTipInteraction</a> and <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.rulerpaninteraction.html" rel="nofollow" target="_blank">RulerPanInteraction</a>.</p>
<p>Unfortunately, I find that while the default interactions set is much more useful than the non-interactive default axes behavior in R2018a and earlier, it could still be improved in two important ways:</p>
<ol>
<li><b>Performance</b> &#8211; Matlab&#8217;s builtin Interaction objects are very inefficient. In cases of multiple overlapping axes (which is very common in multi-tab GUIs or cases of various types of axes), instead of processing events for just the top visible axes, they process all the enabled interactions for *all* axes (including non-visible ones!). This is particularly problematic with the default DataTipInteraction &#8211; it includes a <code>Linger</code> object whose apparent purpose is to detect when the mouse lingers for enough time on top of a chart object, and displays a data-tip in such cases. Its internal code is both inefficient and processed multiple times (for each of the axes), as can be seen via a profiling session.</li>
<li><b>Usability</b> &#8211; In my experience, <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.interactions.regionzoominteraction.html" rel="nofollow" target="_blank">RegionZoomInteraction</a> (which enables defining a region zoom-box via click-&#038;-drag) is usually much more useful than PanInteraction for most plot types. ZoomInteraction, which is enabled by default only enables zooming-in and -out using the mouse-wheel, which is much less useful and more cumbersome to use than RegionZoomInteraction. The panning functionality can still be accessed interactively with the mouse by dragging the X and Y rulers (ticks) to each side.</li>
</ol>
<p>For these reasons, I typically use the following function whenever I create new axes, to replace the default sluggish DataTipInteraction and PanInteraction with RegionZoomInteraction:<br />
<span id="more-10306"></span></p>
<pre lang="matlab">
function axDefaultCreateFcn(hAxes, ~)
    try
        hAxes.Interactions = [zoomInteraction regionZoomInteraction rulerPanInteraction];
        hAxes.Toolbar = [];
    catch
        % ignore - old Matlab release
    end
end
</pre>
<p>The purpose of these two axes property changes shall become apparent below.<br />
This function can either be called directly (<code>axDefaultCreateFcn(hAxes</code>), or as part of the containing figure&#8217;s creation script to ensure than any axes created in this figure has this fix applied:</p>
<pre lang="matlab">
set(hFig,'defaultAxesCreateFcn',@axDefaultCreateFcn);
</pre>
<h3 id="testing">Test setup</h3>
<p><figure style="width: 268px" class="wp-caption alignright"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/Axes_Interactivity.png" alt="Figure with default axes toolbar and interactivity" title="Figure with default axes toolbar and interactivity" width="268" height="200" /><figcaption class="wp-caption-text">Figure with default axes toolbar and interactivity</figcaption></figure> To test the changes, let&#8217;s prepare a figure with 10 tabs, with 10 overlapping panels and a single axes in each tab:</p>
<pre lang="matlab">
hFig = figure('Pos',[10,10,400,300]);
hTabGroup = uitabgroup(hFig);
for iTab = 1 : 10
    hTab = uitab(hTabGroup, 'title',num2str(iTab));
    hPanel = uipanel(hTab);
    for iPanel = 1 : 10
        hPanel = uipanel(hPanel);
    end
    hAxes(iTab) = axes(hPanel); %see MLint note below
    plot(hAxes(iTab),1:5,'-ob');
end
drawnow
</pre>
<p style="padding-left: 20px; margin-top: -15px;"><i><font size=-1>p.s. &#8211; there&#8217;s a incorrect MLint (Code Analyzer) warning in line 9 about the call to axes(hPanel) being inefficient in a loop. Apparently, MLint incorrectly parses this function call as a request to make the axes in-focus, rather than as a request to create the axes in the specified hPanel parent container. We can safely ignore this warning.</font></i></p>
<p>Now let&#8217;s create a run-time test script that simulates 2000 mouse movements using <a href="https://undocumentedmatlab.com/articles/gui-automation-robot" target="_blank">java.awt.Robot</a>:</p>
<pre lang="matlab">
tic
monitorPos = get(0,'MonitorPositions');
y0 = monitorPos(1,4) - 200;
robot = java.awt.Robot;
for iEvent = 1 : 2000
    robot.mouseMove(150, y0+mod(iEvent,100));
    drawnow
end
toc
</pre>
<p>This takes ~45 seconds to run on my laptop: ~23ms per mouse movement on average, with noticeable &#8220;linger&#8221; when the mouse pointer is near the plotted data line. Note that this figure is extremely simplistic &#8211; In a real-life program, the mouse events processing lag the mouse movements, making the GUI far more sluggish than the same GUI on R2018a or earlier. In fact, in one of my more complex GUIs, the entire GUI and Matlab itself came to a standstill that required killing the Matlab process, just by moving the mouse for several seconds.</p>
<p>Notice that at any time, only a single axes is actually visible in our test setup. The other 9 axes are not visible although their <b>Visible</b> property is <code>'on'</code>. Despite this, when the mouse moves within the figure, these other axes unnecessarily process the mouse events.</p>
<h3 id="interactions">Changing the default interactions</h3>
<p>Let&#8217;s modify the axes creation script as I mentioned above, by changing the default interactions (note the highlighted code addition):</p>
<pre lang="matlab" highlight="11">
hFig = figure('Pos',[10,10,400,300]);
hTabGroup = uitabgroup(hFig);
for iTab = 1 : 10
    hTab = uitab(hTabGroup, 'title',num2str(iTab));
    hPanel = uipanel(hTab);
    for iPanel = 1 : 10
        hPanel = uipanel(hPanel);
    end
    hAxes(iTab) = axes(hPanel);
    plot(hAxes(iTab),1:5,'-ob');
    hAxes(iTab).Interactions = [zoomInteraction regionZoomInteraction rulerPanInteraction];
end
drawnow
</pre>
<p>The test script now takes only 12 seconds to run &#8211; 4x faster than the default and yet IMHO with better interactivity (using RegionZoomInteraction).</p>
<h3 id="Toolbar">Effects of the axes toolbar</h3>
<p>The axes-specific toolbar, another innovation of R2018b, does not just have interactivity aspects, which are by themselves <a href="https://undocumentedmatlab.com/articles/reverting-axes-controls-in-figure-toolbar" target="_blank">much-contested</a>. A much less discussed aspect of the axes toolbar is that it degrades the overall performance of axes. The reason is that the axes toolbar&#8217;s transparency, visibility, background color and contents continuously update whenever the mouse moves within the axes area.</p>
<p>Since we have set up the default interactivity to a more-usable set above, and since we can replace the axes toolbar with figure-level toolbar controls, we can simply delete the axes-level toolbars for even more-improved performance:</p>
<pre lang="matlab" highlight="12">
hFig = figure('Pos',[10,10,400,300]);
hTabGroup = uitabgroup(hFig);
for iTab = 1 : 10
    hTab = uitab(hTabGroup, 'title',num2str(iTab));
    hPanel = uipanel(hTab);
    for iPanel = 1 : 10
        hPanel = uipanel(hPanel);
    end
    hAxes(iTab) = axes(hPanel);
    plot(hAxes(iTab),1:5,'-ob');
    hAxes(iTab).Interactions = [zoomInteraction regionZoomInteraction rulerPanInteraction];
    hAxes(iTab).Toolbar = [];
end
drawnow
</pre>
<p>This brings the test script&#8217;s run-time down to 6 seconds &#8211; <b>7x faster than the default run-time</b>. At ~3ms per mouse event, the GUI is now as performant and snippy as in R2018a, even with the new interactive mouse actions of R2018b active.</p>
<h3 id="Conclusions">Conclusions</h3>
<p>MathWorks definitely did not intend for this slow-down aspect, but it is an unfortunate by-product of the choice to auto-enable DataTipInteraction and of its sub-optimal implementation. Perhaps this side-effect was never noticed by MathWorks because the testing scripts probably had only a few axes in a very simple figure &#8211; in such a case the performance lags are very small and might have slipped under the radar. But I assume that many real-life complex GUIs will display significant lags in R2018b and newer Matlab releases, compared to R2018a and earlier releases. I assume that such users will be surprised/dismayed to discover that in R2018b their GUI not only interacts differently but also runs slower, although the program code has not changed.</p>
<p>One of the common claims that I often hear against using undocumented Matlab features is that the program might break in some future Matlab release that would not support some of these features. But users certainly do not expect that their programs might break in new Matlab releases when they only use documented features, as in this case. IMHO, this case (and others over the years) demonstrates that using undocumented features is usually not much riskier than using the standard documented features with regards to future compatibility, making the risk/reward ratio more favorable. In fact, of the ~400 posts that I have published in the past decade (this blog is already 10 years old, time flies&#8230;), very few tips no longer work in the latest Matlab release. When such forward compatibility issues do arise, whether with fully-documented or undocumented features, we can often find workarounds as I have shown above.</p>
<p>If your Matlab program could use a performance boost, I would be happy to assist making your program faster and more responsive. Don&#8217;t hesitate to reach out to me for a consulting quote.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/improving-graphics-interactivity">Improving graphics interactivity</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events" rel="bookmark" title="Undocumented HG2 graphics events">Undocumented HG2 graphics events </a> <small>Matlab's new HG2 graphics engine includes many new undocumented events that could be used in various ways. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/handle-graphics-behavior" rel="bookmark" title="Handle Graphics Behavior">Handle Graphics Behavior </a> <small>HG behaviors are an important aspect of Matlab graphics that enable custom control of handle functionality. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/improving-save-performance" rel="bookmark" title="Improving save performance">Improving save performance </a> <small>There are many different ways of improving Matlab's standard save function performance. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/waterloo-graphics" rel="bookmark" title="Waterloo graphics">Waterloo graphics </a> <small>Waterloo is an open-source library that can significantly improve Matlab GUI. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/improving-graphics-interactivity/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Plot legend customization</title>
		<link>https://undocumentedmatlab.com/articles/plot-legend-customization?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=plot-legend-customization</link>
					<comments>https://undocumentedmatlab.com/articles/plot-legend-customization#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Thu, 12 Jul 2018 14:11:40 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7744</guid>

					<description><![CDATA[<p>Matlab plot legends and their internal components can be customized using a variety of undocumented properties that are easily accessible. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plot-legend-customization">Plot legend customization</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/plot-legend-title" rel="bookmark" title="Plot legend title">Plot legend title </a> <small>Titles to plot legends are easy to achieve in HG1 (R2014a or earlier), but much more difficult in HG2 (R2014b or newer). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-line-transparency-and-color-gradient" rel="bookmark" title="Plot line transparency and color gradient">Plot line transparency and color gradient </a> <small>Static and interpolated (gradient) colors and transparency can be set for plot lines in HG2. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" rel="bookmark" title="Plot markers transparency and color gradient">Plot markers transparency and color gradient </a> <small>Matlab plot-line markers can be customized to have transparency and color gradients. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-column-grid-legend" rel="bookmark" title="Multi-column (grid) legend">Multi-column (grid) legend </a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Three years ago I <a href="/articles/plot-legend-title" target="_blank">explained</a> how we can use a couple of undocumented hidden properties of the legend in order to add a legend title (the legend object had no <b>Title</b> property back then &#8211; this was only added in a later Matlab release, perhaps as a result of my post). Today I will expand on that article by explaining the plot legend&#8217;s internal graphics hierarchy, how we can access each of these components, and then how this information could be used to customize the separate legend components. Note that the discussion today is only relevant for HG2 legends (i.e. R2014b or newer).<br />
Let&#8217;s start with a simple Matlab plot with a legend:</p>
<pre lang="matlab">
hold all;
hLine1 = plot(1:5);
hLine2 = plot(2:6);
hLegend = legend([hLine1,hLine2], 'Location','SouthEast');
hLegend.Title.String = 'MyLegend';
</pre>
<p><center><figure style="width: 210px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_1.gif" alt="Standard Matlab legend" title="Standard Matlab legend" width="210" height="145" /><figcaption class="wp-caption-text">Standard Matlab legend</figcaption></figure></center> This legend is composed of the following visible internal components, which can be customized separately:<br />
<center><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" /></center><br />
<span id="more-7744"></span><br />
<!-- center>[caption id="" align="aligncenter" width="150" caption="Matlab legend components"]<img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" />[/caption]<img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" /></center --><br />
<!-- span class="alignright"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/legend_2018_2.gif" alt="Matlab legend components" title="Matlab legend components" width="150" height="110" /></span --></p>
<table>
<tr>
<th align="left">Id in screenshot</th>
<th align="left">Accessed via</th>
<th align="left">Object type</th>
<th align="left">Description</th>
<th align="left">Important properties</th>
</tr>
<tr>
<td>1</td>
<td><code>hLegend.Title</code></td>
<td><code>Text</code></td>
<td>Title of the legend</td>
<td><b>Visible</b>, <b>String</b>, <b>Color</b>, <b>FontSize</b>, <b>FontWeight</b>.</td>
</tr>
<tr>
<td>2</td>
<td><code>hLegend.TitleSeparator</code></td>
<td><code>LineStrip</code></td>
<td>Separator line between title and legend entries. Only appears when title is set.</td>
<td><b>Visible</b>, <b>LineStyle</b>, <b>LineWidth</b>, <b>ColorData</b> (4&#215;1 uint8)</td>
</tr>
<tr>
<td>3</td>
<td><code>hLegend.BoxEdge</code></td>
<td><code>LineLoop</code></td>
<td>Box (border) line around the entire legend (including title)</td>
<td><b>Visible</b>, <b>LineStyle</b>, <b>LineWidth</b>, <b>ColorData</b> (4&#215;1 uint8)</td</td>
</tr>
<tr>
<td>4</td>
<td><code>hLegend.EntryContainer.NodeChildren(2)</code></td>
<td><code>LegendEntry</code></td>
<td>Entry row in the legend, corresponding to <code>hLine1</code></td>
<td><b>Icon</b>, <b>Label</b>, <b>Object</b> (line object in main axes)</td>
</tr>
<tr>
<td>5</td>
<td><code>hLegend.EntryContainer.NodeChildren(1)</code></td>
<td><code>LegendEntry</code></td>
<td>Entry row in the legend, corresponding to <code>hLine2</code></td>
<td><b>Icon</b>, <b>Label</b>, <b>Object</b> (line object in main axes)</td>
</tr>
<tr>
<td>6</td>
<td><code>hLegend.EntryContainer.NodeChildren(1).Label</code></td>
<td><code>Text</code></td>
<td>Label of legend entry</td>
<td><b>Visible</b>, <b>String</b>, <b>Color</b>, <b>FontSize</b>, <b>FontWeight</b></td>
</tr>
<tr>
<td>7</td>
<td><code>hLegend.EntryContainer.NodeChildren(1).Icon</code></td>
<td><code>LegendIcon</code></td>
<td>Icon/marker of legend entry</td>
<td><b>Visible</b>, <b>Transform.Children.Children</b> (<code>LineStrip</code> object)</td>
</tr>
</table>
<p>A pivotal object of the legend group are the <code>LegendEntry</code> items, one per legend row:</p>
<pre lang="matlab">
>> hLegendEntry = hLegend.EntryContainer.NodeChildren(1);
>> get(hLegendEntry)
              Children: [3×1 Graphics]
                 Color: [0 0 0]
                 Dirty: 0
             FontAngle: 'normal'
              FontName: 'Helvetica'
              FontSize: 8
            FontWeight: 'normal'
      HandleVisibility: 'on'
               HitTest: 'on'
                  Icon: [1×1 LegendIcon]
                 Index: 0
           Interpreter: 'tex'
                 Label: [1×1 Text]
            LayoutInfo: [1×1 matlab.graphics.illustration.legend.ItemLayoutInfo]
                Legend: [1×1 Legend]
              Listener: [1×1 event.listener]
                Object: [1×1 Line]
               Overlay: [1×1 TriangleStrip]
          OverlayAlpha: 0.65
                Parent: [1×1 Group]
           PeerVisible: 'on'
         PickableParts: 'visible'
              Selected: 'off'
    SelectionHighlight: 'on'
               Visible: 'on'
       VisibleListener: [1×1 event.proplistener]
</pre>
<p>Each <code>LegendEntry</code> contains a back-reference to the original graphics object. In my example above, <code>hLegend.EntryContainer.NodeChildren(2).Object == hLine1</code>, and <code>hLegend.EntryContainer.NodeChildren(2).Object == hLine1</code>. Note how the default legend entries order is the reverse of the order of creation of the original graphics objects. Naturally, we can modify this order by creating the legend py passing it an array of handles that is ordered differently (see the documentation of the <i><b>legend</b></i> function).<br />
To get all the original graphic objects together, in a single array, we could use one of two mechanisms (note the different order of the returned objects):</p>
<pre lang="matlab">
% Alternative #1
>> [hLegend.EntryContainer.NodeChildren.Object]'
ans =
  2×1 Line array:
  Line    (data2)
  Line    (data1)
% Alternative #2
>> hLegend.PlotChildren
ans =
  2×1 Line array:
  Line    (data1)
  Line    (data2)
</pre>
<p>For some reason, accessing the displayed graphic line in <code>LegendEntry</code>&#8216;s <b>Icon</b> is not simple. For example, the <code>LineStrip</code> object that corresponds to <code>hLine2</code> can be gotten via:</p>
<pre lang="matlab">
hLegendEntry = hLegend.EntryContainer.NodeChildren(1);
hLegendIconLine = hLegendEntry.Icon.Transform.Children.Children;  % a LineStrip object in our example
</pre>
<p>I assume that this was done to enable non-standard icons for patches and other complex objects (in which case the displayed icon would not necessarily be a <code>LineStrip</code> object). In the case of a line with markers, for example, <code>hLegendIconLine</code> would be an array of 2 objects: a <code>LineStrip</code> object and a separate <code>Marker</code> object. Still, I think that a direct reference in a <code>hLegend.EntryContainer.NodeChildren(1).Icon</code> property would have helped in 99% of all cases, so that we wouldn&#8217;t need to pass through the <code>Transform</code> object.<br />
Anyway, once we have this object reference(s), we can modify its/their properties. In the case of a <code>LineStrip</code> this includes <b>LineStyle</b>, <b>LineWidth</b>, <b>ColorData</b> (4&#215;1 uint8), and <b>VertexData</b> (which controls position/length):</p>
<pre lang="matlab">
>> get(hLegendIconLine(end))  % LineStrip
          AlignVertexCenters: 'on'
             AmbientStrength: 0.3
                ColorBinding: 'object'
                   ColorData: [4×1 uint8]
                   ColorType: 'truecolor'
             DiffuseStrength: 0.6
            HandleVisibility: 'on'
                     HitTest: 'off'
                       Layer: 'middle'
                     LineCap: 'none'
                    LineJoin: 'round'
                   LineStyle: 'solid'
                   LineWidth: 0.5
               NormalBinding: 'none'
                  NormalData: []
                      Parent: [1×1 Group]
               PickableParts: 'visible'
    SpecularColorReflectance: 1
            SpecularExponent: 10
            SpecularStrength: 0.9
                   StripData: []
                     Texture: [0×0 GraphicsPlaceholder]
                  VertexData: [3×2 single]
               VertexIndices: []
                     Visible: 'on'
       WideLineRenderingHint: 'software'
</pre>
<p>and in the presense of markers:</p>
<pre lang="matlab">
>> get(hLegendIconLine(1))  % Marker
    EdgeColorBinding: 'object'
       EdgeColorData: [4×1 uint8]
       EdgeColorType: 'truecolor'
    FaceColorBinding: 'object'
       FaceColorData: []
       FaceColorType: 'truecolor'
    HandleVisibility: 'on'
             HitTest: 'off'
               Layer: 'middle'
           LineWidth: 0.5
              Parent: [1×1 Group]
       PickableParts: 'visible'
                Size: 6
         SizeBinding: 'object'
               Style: 'circle'
          VertexData: [3×1 single]
       VertexIndices: []
             Visible: 'on'
</pre>
<p>An additional undocumented legend property that is of interest is <b>ItemTokenSize</b>. This is a 2-element numeric array specifying the minimal size of the legend entries&#8217; icon and label. By default <code>hLegend.ItemTokenSize == [30,18]</code>, but we can either expand or shrink the icons/labels by setting different values. For example:</p>
<pre lang="matlab">hLegend.ItemTokenSize == [10,1];  % shrink legend icons and labels</pre>
<p>Note that regardless of the amount that we specify, the actual amount that will be used will be such that all legend labels appear.<br />
Fun: try playing with negative values for the icon and the label and see what happens 🙂<br />
Have you come across any other interesting undocumented aspect of Matlab legends? If so, then please share it in a comment below.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plot-legend-customization">Plot legend customization</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/plot-legend-title" rel="bookmark" title="Plot legend title">Plot legend title </a> <small>Titles to plot legends are easy to achieve in HG1 (R2014a or earlier), but much more difficult in HG2 (R2014b or newer). ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-line-transparency-and-color-gradient" rel="bookmark" title="Plot line transparency and color gradient">Plot line transparency and color gradient </a> <small>Static and interpolated (gradient) colors and transparency can be set for plot lines in HG2. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" rel="bookmark" title="Plot markers transparency and color gradient">Plot markers transparency and color gradient </a> <small>Matlab plot-line markers can be customized to have transparency and color gradients. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/multi-column-grid-legend" rel="bookmark" title="Multi-column (grid) legend">Multi-column (grid) legend </a> <small>This article explains how to use undocumented axes listeners for implementing multi-column plot legends...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/plot-legend-customization/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing axes tick labels</title>
		<link>https://undocumentedmatlab.com/articles/customizing-axes-tick-labels?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-axes-tick-labels</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-axes-tick-labels#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 24 Jan 2018 13:38:26 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7304</guid>

					<description><![CDATA[<p>Multiple customizations can be applied to tick labels. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels">Customizing axes tick labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/setting-axes-tick-labels-format" rel="bookmark" title="Setting axes tick labels format">Setting axes tick labels format </a> <small>Matlab plot axes ticks can be customized in a way that will automatically update whenever the tick values change. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels" rel="bookmark" title="Customizing axes part 5 &#8211; origin crossover and labels">Customizing axes part 5 &#8211; origin crossover and labels </a> <small>The axes rulers (axles) can be made to cross-over at any x,y location within the chart. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-2" rel="bookmark" title="Customizing axes part 2">Customizing axes part 2 </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>In <a href="/articles/customizing-histogram-plots" target="_blank">last week&#8217;s post</a>, I discussed various ways to customize bar/histogram plots, including customization of the tick labels. While some of the customizations that I discussed indeed rely on undocumented properties/features, many Matlab users are not aware that tick labels can be individually customized, and that this is a <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.axis.axes-properties.html#property_d119e51283" rel="nofollow" target="_blank">fully documented/supported functionality</a>. This relies on the fact that the default axes <b>TickLabelInterpreter</b> property value is <code>'tex'</code>, which supports a wide range of font customizations, individually for each label. This includes any combination of symbols, superscript, subscript, bold, italic, slanted, face-name, font-size and color &#8211; even intermixed within a single label. Since tex is the default interpreter, we don&#8217;t need any special preparation &#8211; simply set the relevant <b>X/Y/ZTickLabel</b> string to include the relevant tex markup.<br />
To illustrate this, have a look at the following <a href="https://stackoverflow.com/a/46181211/233829" rel="nofollow" target="_blank">excellent answer</a> by user Ubi on Stack Overflow:<br />
<figure style="width: 450px" class="wp-caption alignright"><img loading="lazy" decoding="async" src="https://i.stack.imgur.com/3vjhD.png" alt="Axes with Tex-customized tick labels" title="Axes with Tex-customized tick labels" width="450" height="300" /><figcaption class="wp-caption-text">Axes with Tex-customized tick labels</figcaption></figure></p>
<pre lang="matlab">
plot(1:10, rand(1,10))
ax = gca;
% Simply color an XTickLabel
ax.XTickLabel{3} = ['\color{red}' ax.XTickLabel{3}];
% Use TeX symbols
ax.XTickLabel{4} = '\color{blue} \uparrow';
% Use multiple colors in one XTickLabel
ax.XTickLabel{5} = '\color[rgb]{0,1,0}green\color{orange}?';
% Color YTickLabels with colormap
nColors = numel(ax.YTickLabel);
cm = jet(nColors);
for i = 1:nColors
    ax.YTickLabel{i} = sprintf('\\color[rgb]{%f,%f,%f}%s', cm(i,:), ax.YTickLabel{i});
end
</pre>
<p>In addition to <code>'tex'</code>, we can also set the axes object&#8217;s <b>TickLabelInterpreter</b> to <code>'latex'</code> for a Latex interpreter, or <code>'none'</code> if we want to use no string interpretation at all.<br />
As I showed in <a href="/articles/customizing-histogram-plots" target="_blank">last week&#8217;s post</a>, we can control the gap between the tick labels and the axle line, using the Ruler object&#8217;s undocumented <b>TickLabelGapOffset, TickLabelGapMultiplier</b> properties.<br />
Also, as I explained in other posts (<a href="/articles/customizing-axes-part-5-origin-crossover-and-labels" target="_blank">here</a> and <a href="/articles/customizing-axes-rulers#Exponent" target="_blank">here</a>), we can also control the display of the secondary axle label (typically exponent or units) using the Ruler&#8217;s similarly-undocumented <b>SecondaryLabel</b> property. Note that the related Ruler&#8217;s <b>Exponent</b> property is <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.axis.decorator.numericruler-properties.html" rel="nofollow" target="_blank">documented/supported</a>, but simply sets a basic exponent label (e.g., <code>'\times10^{6}'</code> when <b>Exponent</b>==6) &#8211; to set a custom label string (e.g., <code>'\it\color{gray}Millions'</code>), or to modify its other properties (position, alignment etc.), we should use <b>SecondaryLabel</b>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels">Customizing axes tick labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/setting-axes-tick-labels-format" rel="bookmark" title="Setting axes tick labels format">Setting axes tick labels format </a> <small>Matlab plot axes ticks can be customized in a way that will automatically update whenever the tick values change. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels" rel="bookmark" title="Customizing axes part 5 &#8211; origin crossover and labels">Customizing axes part 5 &#8211; origin crossover and labels </a> <small>The axes rulers (axles) can be made to cross-over at any x,y location within the chart. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-2" rel="bookmark" title="Customizing axes part 2">Customizing axes part 2 </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-axes-tick-labels/feed</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing histogram plots</title>
		<link>https://undocumentedmatlab.com/articles/customizing-histogram-plots?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-histogram-plots</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-histogram-plots#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 17 Jan 2018 20:41:15 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7292</guid>

					<description><![CDATA[<p>Basic bar charts and histogram plots can be customized in important aspects. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-histogram-plots">Customizing histogram plots</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots" rel="bookmark" title="Customizing contour plots">Customizing contour plots </a> <small>Contour labels, lines and fill patches can easily be customized in Matlab HG2. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>Matlab contour labels' color and font can easily be customized. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Earlier today, I was given the task of displaying a histogram plot of a list of values. In today&#8217;s post, I will walk through a few customizations that can be done to bar plots and histograms in order to achieve the desired results.<br />
We start by binning the raw data into pre-selected bins. This can easily be done using the builtin <i><b>histc</b></i> (deprecated) or <i><b>histcounts</b></i> functions. We can then use the <a href="https://www.mathworks.com/help/matlab/ref/bar.html" rel="nofollow" target="_blank"><i><b>bar</b></i> function</a> to plot the results:</p>
<pre lang="matlab">
[binCounts, binEdges] = histcounts(data);
hBars = bar(hAxes, binEdges(1:end-1), binCounts);
</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram1.png" alt="Basic histogram bar plot" title="Basic histogram bar plot" width="400" height="180" /><figcaption class="wp-caption-text">Basic histogram bar plot</figcaption></figure></center><br />
Let&#8217;s improve the appearance: <span id="more-7292"></span>In my specific case, the data was financial return (percentage) values, so let&#8217;s modify the x-label format accordingly and display a title. To make the labels and title more legible, we decrease the axes <b>FontSize</b> to 8 and remove the axes box:</p>
<pre lang="matlab">
hAxes = hBar.Parent;
xtickformat(hAxes, '%g%%');
title(hAxes, 'Distribution of total returns (monthly %)');
set(hAxes, 'FontSize',8, 'Box','off')
</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram2.png" alt="Improved histogram bar plot" title="Improved histogram bar plot" width="400" height="180" /><figcaption class="wp-caption-text">Improved histogram bar plot</figcaption></figure></center><br />
So far nothing undocumented. Note that the <i><b>xtickformat/ytickformat</b></i> functions were only introduced in R2016b &#8211; for earlier Matlab releases <a href="/articles/setting-axes-tick-labels-format" target="_blank">see this post</a> (which does rely on undocumented aspects).<br />
Now, let&#8217;s use a couple of undocumented properties: to remove the excess white-space margin around the axes we&#8217;ll set the axes&#8217; <a href="/articles/axes-looseinset-property" target="_blank"><b>LooseInset</b> property</a>, and to remove the annoying white space between the tick labels and the X-axis we&#8217;ll set the <b>XRuler</b>&#8216;s <b>TickLabelGapOffset</b> property to -2 (default: +2):</p>
<pre lang="matlab">
set(hAxes, 'LooseInset',[0,0,0,0]);    % default = [.13,.11,.095,.075]
hAxes.XRuler.TickLabelGapOffset = -2;  % default = +2
</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram3.png" alt="Even better histogram bar plot" title="Even better histogram bar plot" width="400" height="180" /><figcaption class="wp-caption-text">Even better histogram bar plot</figcaption></figure></center><br />
Note that I used the undocumented axes <b>XRuler</b> property instead of the axes&#8217; documented <a href="https://www.mathworks.com/help/matlab/ref/matlab.graphics.axis.axes-properties.html#prop_XAxis" rel="nofollow" target="_blank"><b>XAxis</b> property</a>, because <b>XAxis</b> is only available since R2015b, whereas <b>XRuler</b> (which points to the exact same object as <b>XAxis</b>) exists ever since R2014b, and so is better from a backward-compatibility standpoint. In either case, the ruler&#8217;s <b>TickLabelGapOffset</b> property is undocumented. Note that the ruler also contains another associated and undocumented <b>TickLabelGapMultiplier</b> property (default: 0.2), which I have not modified in this case.<br />
Now let&#8217;s take a look at the bin labels: The problem with the bar plot above is that it&#8217;s not intuitively clear whether the bin for &#8220;5%&#8221;, for example, includes data between 4.5-5.5 or between 5.0-6.0 (which is the correct answer). It would be nicer if the labels were matched to the actual bin edges. There are 3 basic ways to fix this:</p>
<ol>
<li>We could modify the bar plot axes tick values and labels, in essence &#8220;cheating&#8221; by moving the tick labels half a bin leftward of their tick values (don&#8217;t forget to add the extra tick label on the right):
<pre lang="matlab">
hAxes.XTick(end+1) = hAxes.XTick(end) + 1;  % extra tick label on the right
labels = hAxes.XTickLabels;       % preserve tick labels for later use below
hAxes.XTick = hAxes.XTick - 0.5;  % move tick labels 1/2 bin leftward
hAxes.XTickLabel = labels;        % restore pre-saved tick labels
hAxes.XLim = hAxes.XLim - 0.5;    % ...and align the XLim
</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram4.png" alt="Improved labels" title="Improved labels" width="400" height="180" /><figcaption class="wp-caption-text">Improved labels</figcaption></figure></center>
</li>
<li>We could use the <i><b>bar</b></i> function&#8217;s optional <code>'histc'</code> flag, in order to display the bars in histogram mode. The problem in histogram mode is that while the labels are now placed correctly, the bars touch each other &#8211; I personally find distinct bars that are separated by a small gap easier to understand.
<pre lang="matlab">
hBars = bar(..., 'histc');
% [snip] - same customizations to hAxes as done above
</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram5.png" alt="Basic histogram plot" title="Basic histogram plot" width="400" height="180" /><figcaption class="wp-caption-text">Basic histogram plot</figcaption></figure></center><br />
With the original bar chart we could use the built-in <b>BarWidth</b> to set the bar/gap width (default: 0.8 meaning a 10% gap on either side of the bar). Unfortunately, calling <i><b>bar</b></i> with <code>'hist'</code> or <code>'histc'</code> (i.e. histogram mode) results in a <code>Patch</code> (not <code>Bar</code>) object, and patches do not have a <b>BarWidth</b> property. However, we can modify the resulting patch vertices in order to achieve the same effect:</p>
<pre lang="matlab">
% Modify the patch vertices (5 vertices per bar, row-based)
hBars.Vertices(:,1) = hBars.Vertices(:,1) + 0.1;
hBars.Vertices(4:5:end,1) = hBars.Vertices(4:5:end,1) - 0.2;
hBars.Vertices(5:5:end,1) = hBars.Vertices(5:5:end,1) - 0.2;
% Align the bars & labels at the center of the axes
hAxes.XLim = hAxes.XLim + 0.5;
</pre>
<p>This now looks the same as option #1 above, except that the top-level handle is a <code>Patch</code> (not <code>Bar</code>) object. For various additional customizations, either <code>Patch</code> or <code>Bar</code> might be preferable, so you have a choice.<br />
<center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/histogram4.png" alt="Improved histogram plot" title="Improved histogram plot" width="400" height="180" /><figcaption class="wp-caption-text">Improved histogram plot</figcaption></figure></center>
</li>
<li>Lastly, we could have used the builtin <a href="https://www.mathworks.com/help/matlab/ref/histogram.html" rel="nofollow" target="_blank"><i><b>histogram</b></i> function</a> instead of <i><b>bar</b></i>. This function also displays a plot with touching bars, as above, using <code>Quadrilateral</code> objects (a close relative of <code>Patch</code>). The solution here is very similar to option #2 above, but we need to dig a bit harder to modify the patch faces, since their vertices is not exposed as a public property of the <code>Histogram</code> object. To modify the vertices, we first get the private <b>Face</b> property (<a href="/articles/accessing-private-object-properties" target="_blank">explanation</a>), and then modify its vertices, keeping in mind that in this specific case the bars have 4 vertices per bar and a different vertices matrix orientation:
<pre lang="matlab">
hBars = histogram(data, 'FaceAlpha',1.0, 'EdgeColor','none');
% [snip] - same customizations to hAxes as done above
% Get access to *ALL* the object's properties
oldWarn = warning('off','MATLAB:structOnObject');
warning off MATLAB:hg:EraseModeIgnored
hBarsStruct = struct(hBars);
warning(oldWarn);
% Modify the patch vertices (4 vertices per bar, column-based)
drawnow;  % this is important, won't work without this!
hFace = hBarsStruct.Face;  % a Quadrilateral object (matlab.graphics.primitive.world.Quadrilateral)
hFace.VertexData(1,:) = hFace.VertexData(1,:) + 0.1;
hFace.VertexData(1,3:4:end) = hFace.VertexData(1,3:4:end) - 0.2;
hFace.VertexData(1,4:4:end) = hFace.VertexData(1,4:4:end) - 0.2;
</pre>
</ol>
<p>In conclusion, there are many different ways to improve the appearance of charts in Matlab. Even if at first glance it may seem that some visualization function does not have the requested customization property or feature, a little digging will often find either a relevant undocumented property, or an internal object whose properties could be modified. If you need assistance with customizing your charts for improved functionality and appearance, then consider contacting me for a <a href="/consulting" target="_blank">consulting session</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-histogram-plots">Customizing histogram plots</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots" rel="bookmark" title="Customizing contour plots">Customizing contour plots </a> <small>Contour labels, lines and fill patches can easily be customized in Matlab HG2. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>Matlab contour labels' color and font can easily be customized. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-histogram-plots/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>PlotEdit context-menu customization</title>
		<link>https://undocumentedmatlab.com/articles/plotedit-context-menu-customization?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=plotedit-context-menu-customization</link>
					<comments>https://undocumentedmatlab.com/articles/plotedit-context-menu-customization#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 Dec 2017 12:57:14 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Figure]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7236</guid>

					<description><![CDATA[<p>A combination of Matlab and Java Robot commands to automate a certain animation can be used when we cannot access underlying GUI/graphics code. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plotedit-context-menu-customization">PlotEdit context-menu customization</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-context-menu-to-uitree" rel="bookmark" title="Adding a context-menu to a uitree">Adding a context-menu to a uitree </a> <small>uitree is an undocumented Matlab function, which does not easily enable setting a context-menu. Here's how to do it....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/context-sensitive-help" rel="bookmark" title="Context-Sensitive Help">Context-Sensitive Help </a> <small>Matlab has a hidden/unsupported built-in mechanism for easy implementation of context-sensitive help...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-workspace-context-menu" rel="bookmark" title="Customizing Workspace context-menu">Customizing Workspace context-menu </a> <small>Matlab's Workspace table context-menu can be configured with user-defined actions - this article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitable-customization-report" rel="bookmark" title="Uitable customization report">Uitable customization report </a> <small>Matlab's uitable can be customized in many different ways. A detailed report explains how. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Last week, <a href="https://www.mathworks.com/matlabcentral/answers/370545-prompt-user-before-clearing-axis-when-using-the-clear-axes-context-menu" rel="nofollow" target="_blank">a Matlab user asked</a> whether it is possible to customize the context (right-click) menu that is presented in plot-edit mode. This menu is displayed by clicking the plot-edit (arrow) icon on the standard Matlab figure toolbar, then right-clicking any graphic/GUI element in the figure. Unfortunately, it seems that this context menu is only created the first time that a user right-clicks in plot-edit mode &#8211; it is not accessible before then, and so it seems impossible to customize the menu before it is presented to the user the first time.<br />
<center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Customized plot-edit context-menu" src="https://undocumentedmatlab.com/images/PlotEdit_context_menu.png" title="Customized plot-edit context-menu" width="400" height="337" /><figcaption class="wp-caption-text">Customized plot-edit context-menu</figcaption></figure></center><br />
A few workarounds <a href="https://www.mathworks.com/matlabcentral/answers/370545-prompt-user-before-clearing-axis-when-using-the-clear-axes-context-menu" rel="nofollow" target="_blank">were suggested</a> to the original poster and you are most welcome to review them. There is also some discussion about the technical reasons that none of the &#8220;standard&#8221; ways of finding and modifying menu items fail in this case.<br />
In today&#8217;s post I wish to repost my solution, in the hope that it might help other users in similar cases.<br />
My solution is basically this:<br />
<span id="more-7236"></span></p>
<ol>
<li>First, enter plot-edit mode programmatically using the <i><b>plotedit</b></i> function</li>
<li>Next, move the mouse to the screen location of the relevant figure component (e.g. axes). This can be done in several different ways (the root object&#8217;s <b>PointerLocation</b> property, the <a href="/articles/undocumented-mouse-pointer-functions" target="_blank">moveptr</a> function, or <a href="/articles/gui-automation-robot" target="_blank"><code>java.awt.Robot.<i>mouseMove()</i></code></a> method).</li>
<li>Next, automate a mouse right-click using the built in <a href="https://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html" rel="nofollow" target="_blank"><code>java.awt.Robot</code></a> class (as <a href="/articles/gui-automation-robot" target="_blank">discussed in this blog</a> back in 2010)</li>
<li>Next, locate the relevant context-menu item and modify its label, callback or any of its other properties</li>
<li>Next, dismiss the context-menu by simulating a follow-on right-click using the same <code>Robot</code> object</li>
<li>Finally, exit plot-edit mode and return the mouse pointer to its original location</li>
</ol>
<pre lang="matlab">
% Create an initial figure / axes for demostration purpose
fig = figure('MenuBar','none','Toolbar','figure');
plot(1:5); drawnow;
% Enter plot-edit mode temporarily
plotedit(fig,'on'); drawnow
% Preserve the current mouse pointer location
oldPos = get(0,'PointerLocation');
% Move the mouse pointer to within the axes boundary
% ref: https://undocumentedmatlab.com/articles/undocumented-mouse-pointer-functions
figPos = getpixelposition(fig);   % figure position
axPos  = getpixelposition(gca,1); % axes position
figure(fig);  % ensure that the figure is in focus
newPos = figPos(1:2) + axPos(1:2) + axPos(3:4)/4;  % new pointer position
set(0,'PointerLocation',newPos);  % alternatives: moveptr(), java.awt.Robot.mouseMove()
% Simulate a right-click using Java robot
% ref: https://undocumentedmatlab.com/articles/gui-automation-robot
robot = java.awt.Robot;
robot.mousePress  (java.awt.event.InputEvent.BUTTON3_MASK); pause(0.1)
robot.mouseRelease(java.awt.event.InputEvent.BUTTON3_MASK); pause(0.1)
% Modify the <clear-axes> menu item
hMenuItem = findall(fig,'Label','Clear Axes');
if ~isempty(hMenuItem)
   label = '<html><b><i><font color="blue">Undocumented Matlab';
   callback = 'web(''https://undocumentedmatlab.com'',''-browser'');';
   set(hMenuItem, 'Label',label, 'Callback',callback);
end
% Hide the context menu by simulating a left-click slightly offset
set(0,'PointerLocation',newPos+[-2,2]);  % 2 pixels up-and-left
pause(0.1)
robot.mousePress  (java.awt.event.InputEvent.BUTTON1_MASK); pause(0.1)
robot.mouseRelease(java.awt.event.InputEvent.BUTTON1_MASK); pause(0.1)
% Exit plot-edit mode
plotedit(fig,'off'); drawnow
% Restore the mouse pointer to its previous location
set(0,'PointerLocation',oldPos);
</pre>
<p>In this code, I sprinkled a few <i><b>pause</b></i>s at several locations, to ensure that everything has time to fully render. Different pause values, or perhaps no pause at all, may be needed on your specific system.<br />
Modifying the default context-menu shown in plot-edit mode may perhaps be an uncommon use-case. But the technique that I demonstrated above &#8211; of using a combination of Matlab and Java <code>Robot</code> commands to automate a certain animation &#8211; can well be used in many other use-cases where we cannot easily access the underlying code. For example, when the internal code is encoded/encrypted, or when a certain functionality (such as the plot-edit context-menu) is created on-the-fly.<br />
If you have encountered a similar use-case where such automated animations can be used effectively, please add a comment below. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/plotedit-context-menu-customization">PlotEdit context-menu customization</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-context-menu-to-uitree" rel="bookmark" title="Adding a context-menu to a uitree">Adding a context-menu to a uitree </a> <small>uitree is an undocumented Matlab function, which does not easily enable setting a context-menu. Here's how to do it....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/context-sensitive-help" rel="bookmark" title="Context-Sensitive Help">Context-Sensitive Help </a> <small>Matlab has a hidden/unsupported built-in mechanism for easy implementation of context-sensitive help...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-workspace-context-menu" rel="bookmark" title="Customizing Workspace context-menu">Customizing Workspace context-menu </a> <small>Matlab's Workspace table context-menu can be configured with user-defined actions - this article explains how....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitable-customization-report" rel="bookmark" title="Uitable customization report">Uitable customization report </a> <small>Matlab's uitable can be customized in many different ways. A detailed report explains how. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/plotedit-context-menu-customization/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing contour plots part 2</title>
		<link>https://undocumentedmatlab.com/articles/customizing-contour-plots-part2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-contour-plots-part2</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-contour-plots-part2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Sun, 12 Nov 2017 11:03:37 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7149</guid>

					<description><![CDATA[<p>Matlab contour labels' color and font can easily be customized. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part2">Customizing contour plots part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots" rel="bookmark" title="Customizing contour plots">Customizing contour plots </a> <small>Contour labels, lines and fill patches can easily be customized in Matlab HG2. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-histogram-plots" rel="bookmark" title="Customizing histogram plots">Customizing histogram plots </a> <small>Basic bar charts and histogram plots can be customized in important aspects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few weeks ago a user posted a question on Matlab&#8217;s Answers forum, asking whether it is possible to <a href="https://www.mathworks.com/matlabcentral/answers/363059-how-do-i-label-a-contour-plot-in-the-same-colors-as-the-contour-lines" rel="nofollow" target="_blank">display contour labels in the same color as their corresponding contour lines</a>. In today&#8217;s post I&#8217;ll provide some insight that may assist users with similar customizations in other plot types.<br />
Matlab does not provide, for reasons that escape my limited understanding, documented access to the contour plot&#8217;s component primitives, namely its contour lines, labels and patch faces. Luckily however, these handles are accessible (in HG2, i.e. R2014b onward) via undocumented hidden properties aptly named <b>EdgePrims</b>, <b>TextPrims</b> and <b>FacePrims</b>, as I explained in a previous post about <a href="/articles/customizing-contour-plots" target="_blank">contour plots customization</a>, two years ago.<br />
Let&#8217;s start with a simple contour plot of the <i><b>peaks</b></i> function:</p>
<pre lang="matlab">
[X,Y,Z] = peaks;
[C,hContour] = contour(X,Y,Z, 'ShowText','on', 'LevelStep',1);
</pre>
<p>The result is the screenshot on the left:<br />
<center><figure style="width: 454px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Standard Matlab contour labels" src="https://undocumentedmatlab.com/images/contour_labels_1b.png" title="Standard Matlab contour labels" width="454" height="367" /><figcaption class="wp-caption-text">Standard Matlab contour labels</figcaption></figure> &nbsp; <figure style="width: 454px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Customized Matlab contour labels" src="https://undocumentedmatlab.com/images/contour_labels_2b.png" title="Customized Matlab contour labels" width="454" height="367" /><figcaption class="wp-caption-text">Customized Matlab contour labels</figcaption></figure></center><br />
In order to update the label colors (to get the screenshot on the right), we create a short <code>updateContours</code> function that updates the <b>TextPrims</b> color to their corresponding <b>EdgePrims</b> color:<br />
<span id="more-7149"></span></p>
<h3 id="updateContours">The updateContours() function</h3>
<pre lang="matlab">
function updateContours(hContour)
    % Update the text label colors
    drawnow  % very important!
    levels = hContour.LevelList;
    labels = hContour.TextPrims;  % undocumented/unsupported
    lines  = hContour.EdgePrims;  % undocumented/unsupported
    for idx = 1 : numel(labels)
        labelValue = str2double(labels(idx).String);
        lineIdx = find(abs(levels-labelValue)<10*eps, 1);  % avoid FP errors using eps
        labels(idx).ColorData = lines(lineIdx).ColorData;  % update the label color
        %labels(idx).Font.Size = 8;                        % update the label font size
    end
    drawnow  % optional
end
</pre>
<p>Note that in this function we don't directly equate the numeric label values to the contour levels' values: this would work well for integer values but would fail with floating-point ones. Instead I used a very small <code>10*eps</code> tolerance in the numeric comparison.<br />
Also note that I was careful to call <i><b>drawnow</b></i> at the top of the update function, in order to ensure that <b>EdgePrims</b> and <b>TextPrims</b> are updated when the function is called (this might not be the case before the call to <i><b>drawnow</b></i>). The final <i><b>drawnow</b></i> at the end of the function is optional: it is meant to reduce the flicker caused by the changing label colors, but it can be removed to improve the rendering performance in case of rapidly-changing contour plots.<br />
Finally, note that I added a commented line that shows we can modify other label properties (in this case, the font size from 10 to 8). Feel free to experiment with other label properties.</p>
<h3 id="summary">Putting it all together</h3>
<p>The final stage is to call our new <code>updateContours</code> function directly, immediately after creating the contour plot. We also want to call <code>updateContours</code> asynchronously whenever the contour is redrawn, for example, upon a zoom/pan event, or when one of the relevant contour properties (e.g., <b>LevelStep</b> or <b>*Data</b>) changes. To do this, we add a callback listener to the contour object's [undocumented] <a href="/articles/undocumented-hg2-graphics-events" target="_blank"><b>MarkedClean</b> event</a> that reruns our <code>updateContours</code> function:</p>
<pre lang="matlab">
[X,Y,Z] = peaks;
[C,hContour] = contour(X,Y,Z, 'ShowText','on', 'LevelStep',1);
% Update the contours immediately, and also whenever the contour is redrawn
updateContours(hContour);
addlistener(hContour, 'MarkedClean', @(h,e)updateContours(hContour));
</pre>
<h3 id="">Contour level values</h3>
<p>As noted in my <a href="/articles/customizing-contour-plots-part2#comment-416543">comment reply</a> below, the contour lines (hContour.<b>EdgePrims</b>) correspond to the contour levels (hContour.<b>LevelList</b>).<br />
For example, to make all negative contour lines dotted, you can do the following:</p>
<pre lang="matlab">
[C,hContour] = contour(peaks, 'ShowText','on', 'LevelStep',1); drawnow
set(hContour.EdgePrims(hContour.LevelList<0), 'LineStyle', 'dotted');
</pre>
<p><center><figure style="width: 455px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Customized Matlab contour lines" src="https://undocumentedmatlab.com/images/contour_labels_3.png" title="Customized Matlab contour lines" width="455" height="363" /><figcaption class="wp-caption-text">Customized Matlab contour lines</figcaption></figure></center></p>
<h3 id="future">Prediction about forward compatibility</h3>
<p>As I noted on my <a href="/articles/customizing-contour-plots" target="_blank">previous post on contour plot customization</a>, I am marking this article as "<a target="_blank" href="/articles/category/presumed-future-risk/high-risk-of-breaking-in-future-versions">High risk of breaking in future Matlab versions</a>", not because of the basic functionality (being important enough I don't presume it will go away anytime soon) but because of the property names: <b>TextPrims</b>, <b>EdgePrims</b> and <b>FacePrims</b> don't seem to be very user-friendly property names. So far MathWorks has been very diligent in making its object properties have meaningful names, and so I assume that when the time comes to expose these properties, they will be renamed (perhaps to <b>TextHandles</b>, <b>EdgeHandles</b> and <b>FaceHandles</b>, or perhaps <b>LabelHandles</b>, <b>LineHandles</b> and <b>FillHandles</b>). For this reason, even if you find out in some future Matlab release that <b>TextPrims</b>, <b>EdgePrims</b> and <b>FacePrims</b> don't exist, perhaps they still exist and simply have different names. Note that these properties have not changed their names or functionality in the past 3 years, so while it could well happen next year, it could also remain unchanged for many years to come. The exact same thing can be said for the <b>MarkedClean</b> event.</p>
<h3 id="consulting">Professional assistance anyone?</h3>
<p>As shown by this and many other posts on this site, a polished interface and functionality is often composed of small professional touches, many of which are not exposed in the official Matlab documentation for various reasons. So if you need top-quality professional appearance/functionality in your Matlab program, or maybe just a Matlab program that is dependable, robust and highly-performant, consider employing my <a href="/consulting" target="_blank">consulting services</a>. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part2">Customizing contour plots part 2</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots" rel="bookmark" title="Customizing contour plots">Customizing contour plots </a> <small>Contour labels, lines and fill patches can easily be customized in Matlab HG2. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-histogram-plots" rel="bookmark" title="Customizing histogram plots">Customizing histogram plots </a> <small>Basic bar charts and histogram plots can be customized in important aspects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-contour-plots-part2/feed</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
			</item>
		<item>
		<title>Matlab GUI training seminars &#8211; Zurich, 29-30 August 2017</title>
		<link>https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matlab-gui-training-seminars-zurich-29-30-august-2017</link>
					<comments>https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Fri, 04 Aug 2017 09:37:52 +0000</pubDate>
				<category><![CDATA[Public presentation]]></category>
		<category><![CDATA[AppDesigner]]></category>
		<category><![CDATA[Callbacks]]></category>
		<category><![CDATA[Figure]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[GUIDE]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JIDE]]></category>
		<category><![CDATA[training]]></category>
		<category><![CDATA[uicontrol]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6992</guid>

					<description><![CDATA[<p>Advanced Matlab training courses on Matlab User Interfaces (GUI) will be presented in Zurich Switzerland on 29-30 August, 2017</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017">Matlab GUI training seminars &#8211; Zurich, 29-30 August 2017</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-expo-bern-22-june-2017" rel="bookmark" title="Matlab Expo &#8211; Bern, 22 June 2017">Matlab Expo &#8211; Bern, 22 June 2017 </a> <small>I will be speaking about easy-to-use Matlab tricks at the upcoming Matlab Expo in Bern, Switzerland on June 22, 2017. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/findjobj-find-underlying-java-object" rel="bookmark" title="FindJObj &#8211; find a Matlab component&#039;s underlying Java object">FindJObj &#8211; find a Matlab component&#039;s underlying Java object </a> <small>The FindJObj utility can be used to access and display the internal components of Matlab controls and containers. This article explains its uses and inner mechanism....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/images-in-matlab-uicontrols-and-labels" rel="bookmark" title="Images in Matlab uicontrols &amp; labels">Images in Matlab uicontrols &amp; labels </a> <small>Images can be added to Matlab controls and labels in a variety of manners, documented and undocumented. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/training" rel="bookmark" title="New training courses">New training courses </a> <small>I am now offering a new service of professional Matlab training, at your location. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><span class="alignright"><img loading="lazy" decoding="async" alt="Advanced Matlab training, Zurich 29-30 August 2017" src="https://undocumentedmatlab.com/images/20140520_153734a_500x321.jpg" title="Advanced Matlab training, Zurich 29-30 August 2017" width="400" height="257"/></span><br />
Advanced Matlab training courses/seminars will be presented by me (Yair) in Zürich, Switzerland on 29-30 August, 2017:</p>
<ul>
<li>August 29 (full day) &#8211; <b>Interactive Matlab GUI</b></li>
<p> <!-- - US$399 (CHF 390.-) ($100 discount if paid by July 31) --></p>
<li>August 30 (full day) &#8211; <b>Advanced Matlab GUI</b></li>
<p> <!-- - US$399 (CHF 390.-) ($100 discount if paid by July 31) --><br />
	<!-- li>Enroll to both courses (2 full days) for a total price of US$699 (CHF 680.-)</li --> <!-- ($150 extra discount if paid by July 31) -->
</ul>
<p><!-- b>Both seminars are confirmed</b>: they do not depend on a minimal number of participants. But there is a limit on the total number of participants, so the sooner you enroll, the more likely you are to get a seat. --><br />
The seminars are targeted at Matlab users who wish to improve their program&#8217;s usability and professional appearance. Basic familiarity with the Matlab environment and coding/programming is assumed. The courses will present a mix of both documented and undocumented aspects, which is not available anywhere else. The curriculum is listed below.<br />
This is a unique opportunity to enhance your Matlab coding skills and improve your program&#8217;s usability in a couple of days<!-- , at a very affordable cost -->.<br />
If you are interested in either or both of these seminars, please <a href="mailto:%20altmany%20@gmail.com?subject=Matlab%20training%20Zurich&amp;body=Hi%20Yair,%20&amp;cc=;&amp;bcc=" rel="nofollow" target="_blank" onclick="var n='altmany'; var d='gmail.com'; window.open('mailto:'+n+'@'+d+'?subject=Matlab training Zurich&amp;body=Hi Yair, '); return false;">Email me</a> (altmany at gmail dot com).<br />
I can also schedule a dedicated visit to your location, for onsite Matlab training customized to your organization&#8217;s specific needs. Additional information can be found on my <a target="_blank" href="/training/">Training page</a>.<br />
Around the time of the training, I will be traveling to various locations around Switzerland. <!-- in Geneva (Aug 22-27), Bern (Aug 27-28), Zürich (Aug 28-30), and Basel (Aug 30 - Sep 3) --> If you wish to meet me in person to discuss how I could bring value to your project, then please email me (altmany at gmail):</p>
<ul>
<li>Geneva: Aug 22 &#8211; 27</li>
<li>Bern: Aug 27 &#8211; 28</li>
<li>Zürich: Aug 28 &#8211; 30</li>
<li>Stuttgart: Aug 30 &#8211; 31</li>
<li>Basel: Sep 1 &#8211; 3</li>
</ul>
<p><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/email-icon.png" width="32" height="22" alt="" style="vertical-align:middle;border:0"/>&nbsp;<a href="mailto: altmany @gmail.com?subject=Matlab consulting/training&#038;body=Hi Yair, &#038;cc=;&#038;bcc=" rel="nofollow" target="_blank" onclick="var n='altmany'; var d='gmail.com'; window.open('mailto:'+n+'@'+d+'?subject=Matlab consulting/training&#038;body=Hi Yair, '); return false;">Email me</a><br />
<span id="more-6992"></span></p>
<hr/>
<h3 id="GUI">Interactive Matlab GUI &#8211; 29 August, 2017</h3>
<ol>
<li>Introduction to Matlab Graphical User Interfaces (GUI)
<ul>
<li>Design principles and best practices</li>
<li>Matlab GUI alternatives</li>
<li>Typical evolution of Matlab GUI developers</li>
</ul>
</li>
<li>GUIDE – MATLAB&#8217;s GUI Design Editor
<ul>
<li>Using GUIDE to design a custom GUI</li>
<li>Available built-in MATLAB uicontrols</li>
<li>Customizing uicontrols</li>
<li>Important figure and uicontrol properties</li>
<li>GUIDE utility windows</li>
<li>The GUIDE-generated file-duo</li>
</ul>
</li>
<li>Customizing GUI appearance and behavior
<ul>
<li>Programmatic GUI creation and control</li>
<li>GUIDE vs. m-programming</li>
<li>Attaching callback functionality to GUI components</li>
<li>Sharing data between GUI components</li>
<li>The handles data struct</li>
<li>Using handle visibility</li>
<li>Position, size and units</li>
<li>Formatting GUI using HTML</li>
</ul>
</li>
<li>Uitable
<ul>
<li>Displaying data in a MATLAB GUI uitable</li>
<li>Controlling column data type</li>
<li>Customizing uitable appearance</li>
<li>Reading uitable data</li>
<li>Uitable callbacks</li>
<li>Additional customizations using Java</li>
</ul>
</li>
<li>Matlab&#8217;s new App Designer and web-based GUI
<ul>
<li>App Designer environment, widgets and code</li>
<li>The web-based future of Matlab GUI and assumed roadmap</li>
<li>App Designer vs. GUIDE – pros and cons comparison</li>
</ul>
</li>
<li>Performance and interactivity considerations
<ul>
<li>Speeding up the initial GUI generation</li>
<li>Improving GUI responsiveness</li>
<li>Actual vs. perceived performance</li>
<li>Continuous interface feedback</li>
<li>Avoiding common performance pitfalls</li>
<li>Tradeoff considerations</li>
</ul>
</li>
</ol>
<p><!-- Throughout the day, a sample data-structure container class will be developed and presented in phases, illustrating the points discussed in the presentation, along with suggestions and discussion on design alternatives, programming quality, efficiency, robustness, maintainability, and performance. In other words, the seminar will include not just a formal presentation of the material but also a live annotated development of a real-world Matlab class that illustrates the presented topics. --><br />
At the end of this seminar, you will have learned how to:</p>
<ul>
<li>apply GUI design principles in Matlab</li>
<li>create simple Matlab GUIs</li>
<li>manipulate and customize graphs, images and GUI components</li>
<li>display Matlab data in a variety of GUI manners, including data tables</li>
<li>decide between using GUIDE, App Designer and/or programmatic GUI</li>
<li>understand tradeoffs in design and run-time performance</li>
<li>comprehend performance implications, to improve GUI speed and responsiveness</li>
</ul>
<hr/>
<h3 id="AMG">Advanced Matlab GUI &#8211; 30 August, 2017</h3>
<ol>
<li>Advanced topics in Matlab GUI
<ul>
<li>GUI callback interrupts and re-entrancy</li>
<li>GUI units and resizing</li>
<li>Advanced HTML formatting</li>
<li>Using hidden (undocumented) properties</li>
<li>Listening to action and property-change events</li>
<li>Uitab, uitree, uiundo and other uitools</li>
</ul>
</li>
<li>Customizing the figure window
<ul>
<li>Creating and customizing the figure&#8217;s main menu</li>
<li>Creating and using context menus</li>
<li>Creating and customizing figure toolbars</li>
</ul>
</li>
<li>Using Java with Matlab GUI
<ul>
<li>Matlab and Java Swing</li>
<li>Integrating Java controls in Matlab GUI</li>
<li>Handling Java events as Matlab callbacks</li>
<li>Integrating built-in Matlab controls/widgets</li>
<li>Integrating JIDE&#8217;s advanced features and professional controls</li>
<li>Integrating 3rd-party Java components: charts/graphs/widgets/reports</li>
</ul>
</li>
<li>Advanced Matlab-Java GUI
<ul>
<li>Customizing standard Matlab uicontrols</li>
<li>Figure-level customization (maximize/minimize, disable etc.)</li>
<li>Containers and position – Matlab vs. Java</li>
<li>Compatibility aspects and trade-offs</li>
<li>Safe programming with Java in Matlab</li>
<li>Java&#8217;s EDT and timing considerations</li>
<li>Deployment (compiler) aspects</li>
</ul>
</li>
</ol>
<p>At the end of this seminar, you will have learned how to:</p>
<ul>
<li>customize the figure toolbar and main menu</li>
<li>use HTML to format GUI appearance</li>
<li>integrate Java controls in Matlab GUI</li>
<li>customize your Matlab GUI to a degree that you never knew was possible</li>
<li>create a modern-looking professional GUI in Matlab</li>
</ul>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017">Matlab GUI training seminars &#8211; Zurich, 29-30 August 2017</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/matlab-expo-bern-22-june-2017" rel="bookmark" title="Matlab Expo &#8211; Bern, 22 June 2017">Matlab Expo &#8211; Bern, 22 June 2017 </a> <small>I will be speaking about easy-to-use Matlab tricks at the upcoming Matlab Expo in Bern, Switzerland on June 22, 2017. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/findjobj-find-underlying-java-object" rel="bookmark" title="FindJObj &#8211; find a Matlab component&#039;s underlying Java object">FindJObj &#8211; find a Matlab component&#039;s underlying Java object </a> <small>The FindJObj utility can be used to access and display the internal components of Matlab controls and containers. This article explains its uses and inner mechanism....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/images-in-matlab-uicontrols-and-labels" rel="bookmark" title="Images in Matlab uicontrols &amp; labels">Images in Matlab uicontrols &amp; labels </a> <small>Images can be added to Matlab controls and labels in a variety of manners, documented and undocumented. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/training" rel="bookmark" title="New training courses">New training courses </a> <small>I am now offering a new service of professional Matlab training, at your location. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/matlab-gui-training-seminars-zurich-29-30-august-2017/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing axes part 5 &#8211; origin crossover and labels</title>
		<link>https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-axes-part-5-origin-crossover-and-labels</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 27 Jul 2016 17:00:02 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6564</guid>

					<description><![CDATA[<p>The axes rulers (axles) can be made to cross-over at any x,y location within the chart. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels">Customizing axes part 5 &#8211; origin crossover and labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-2" rel="bookmark" title="Customizing axes part 2">Customizing axes part 2 </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-4-additional-properties" rel="bookmark" title="Customizing axes part 4 &#8211; additional properties">Customizing axes part 4 &#8211; additional properties </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>When HG2 graphics was finally released in R2014b, I posted a series of articles about various undocumented ways by which we can customize Matlab&#8217;s new graphic axes: <a href="/articles/customizing-axes-rulers" target="_blank">rulers (axles)</a>, <a href="/articles/customizing-axes-part-2" target="_blank">baseline, box-frame, grid</a>, <a href="/articles/customizing-axes-part-3-backdrop" target="_blank">back-drop</a>, and <a href="/articles/customizing-axes-part-4-additional-properties" rel="nofollow" target="_blank">other aspects</a>. Today I extend this series by showing how we can customize the axes rulers&#8217; crossover location.<br />
<center><figure style="width: 337px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Non-default axes crossover location" src="https://undocumentedmatlab.com/images/axes_origin4.png" title="Non-default axes crossover location" width="337" height="306" /><figcaption class="wp-caption-text">Non-default axes crossover location</figcaption></figure></center><br />
<span id="more-6564"></span></p>
<h3 id="documented">The documented/supported stuff</h3>
<p>Until R2015b, we could only specify the axes&#8217; <b>YAxisLocation</b> as <code>'left'</code> (default) or <code>'right'</code>, and <b>XAxisLocation</b> as <code>'bottom'</code> (default) or <code>'top'</code>. For example:</p>
<pre lang="matlab">
x = -2*pi : .01 : 2*pi;
plot(x, sin(x));
hAxis = gca;
hAxis.YAxisLocation = 'left';    % 'left' (default) or 'right'
hAxis.XAxisLocation = 'bottom';  % 'bottom' (default) or 'top'
</pre>
<p><center><figure style="width: 338px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Default axis locations: axes crossover is non-fixed" src="https://undocumentedmatlab.com/images/axes_origin1.png" title="Default axis locations: axes crossover is non-fixed" width="338" height="302" /><figcaption class="wp-caption-text">Default axis locations: axes crossover is non-fixed</figcaption></figure></center><br />
The crossover location is <i>non-fixed</i> in the sense that if we zoom or pan the plot, the axes crossover will remain at the bottom-left corner, which changes its coordinates depending on the X and Y axes limits.<br />
<a href="http://www.mathworks.com/help/matlab/ref/axes-properties.html#property_xaxislocation" rel="nofollow" target="_blank">Since R2016a</a>, we can also specify <code>'origin'</code> for either of these properties, such that the X and/or Y axes pass through the chart origin (0,0) location. For example, move the <b>YAxisLocation</b> to the origin:</p>
<pre lang="matlab">hAxis.YAxisLocation = 'origin';</pre>
<p><center><figure style="width: 338px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Y-axis location at origin: axes crossover at 0 (fixed), -1 (non-fixed)" src="https://undocumentedmatlab.com/images/axes_origin2.png" title="Y-axis location at origin: axes crossover at 0 (fixed), -1 (non-fixed)" width="338" height="306" /><figcaption class="wp-caption-text">Y-axis location at origin: axes crossover at 0 (fixed), -1 (non-fixed)</figcaption></figure></center><br />
And similarly also for <b>XAxisLocation</b>:</p>
<pre lang="matlab">hAxis.XAxisLocation = 'origin';</pre>
<p><center><figure style="width: 337px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="X and Y-axis location at origin: axes crossover fixed at (0,0)" src="https://undocumentedmatlab.com/images/axes_origin3.png" title="X and Y-axis location at origin: axes crossover fixed at (0,0)" width="337" height="306" /><figcaption class="wp-caption-text">X and Y-axis location at origin: axes crossover fixed at (0,0)</figcaption></figure></center><br />
The axes crossover location is now fixed at the origin (0,0), so as we move or pan the plot, the crossover location changes its position in the chart area, without changing its coordinates. This functionality has existed in other graphic packages (outside Matlab) for a long time and until now required quite a bit of coding to emulate in Matlab, so I&#8217;m glad that we now have it in Matlab by simply updating a single property value. MathWorks did a very nice job here of dynamically updating the axles, ticks and labels as we pan (drag) the plot towards the edges &#8211; try it out!</p>
<h3 id="undocumented">The undocumented juicy stuff</h3>
<p>So far for the documented stuff. The undocumented aspect is that we are not limited to using the (0,0) origin point as the fixed axes crossover location. We can use any x,y crossover location, using the <b>FirstCrossoverValue</b> property of the axes&#8217; hidden <b>XRuler</b> and <b>YRuler</b> properties. In fact, <b>we could do this since R2014b</b>, when the new HG2 graphics engine was released, not just starting in R2016a!</p>
<pre lang="matlab">
% Set a fixed crossover location of (pi/2,-0.4)
hAxis.YRuler.FirstCrossoverValue = pi/2;
hAxis.XRuler.FirstCrossoverValue = -0.4;
</pre>
<p><center><figure style="width: 337px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom fixed axes crossover location at (&pi;/2,-0.4)" src="https://undocumentedmatlab.com/images/axes_origin4.png" title="Custom fixed axes crossover location at (&pi;/2,-0.4)" width="337" height="306" /><figcaption class="wp-caption-text">Custom fixed axes crossover location at (&pi;/2,-0.4)</figcaption></figure></center><br />
For some reason (bug?), setting <b>XAxisLocation</b>/<b>YAxisLocation</b> to &#8216;origin&#8217; has no visible effect in 3D plots, nor is there any corresponding <b>ZAxisLocation</b> property. Luckily, we can set the axes crossover location(s) in 3D plots using <b>FirstCrossoverValue</b> just as easily as for 2D plots. The rulers also have a <b>SecondCrossoverValue</b> property (default = -inf) that controls the Z-axis crossover, as Yaroslav <a href="/articles/customizing-axes-part-5-origin-crossover-and-labels#comment-384290">pointed out</a> in a comment below. For example:</p>
<pre lang="matlab">
N = 49;
x = linspace(-10,10,N);
M = peaks(N);
mesh(x,x,M);
</pre>
<p><center><figure style="width: 442px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Default crossover locations at (-10,&plusmn;10,-10)" src="https://undocumentedmatlab.com/images/axes_origin_3D1.png" title="Default crossover locations at (-10,&plusmn;10,-10)" width="442" height="249" /><figcaption class="wp-caption-text">Default crossover locations at (-10,&plusmn;10,-10)</figcaption></figure></center></p>
<pre lang="matlab">
hAxis.XRuler.FirstCrossoverValue  = 0; % X crossover with Y axis
hAxis.YRuler.FirstCrossoverValue  = 0; % Y crossover with X axis
hAxis.ZRuler.FirstCrossoverValue  = 0; % Z crossover with X axis
hAxis.ZRuler.SecondCrossoverValue = 0; % Z crossover with Y axis
</pre>
<p><center><figure style="width: 390px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom fixed axes crossover location at (0,0,-10)" src="https://undocumentedmatlab.com/images/axes_origin_3D2.png" title="Custom fixed axes crossover location at (0,0,-10)" width="390" height="230" /><figcaption class="wp-caption-text">Custom fixed axes crossover location at (0,0,-10)</figcaption></figure></center></p>
<pre lang="matlab">
hAxis.XRuler.SecondCrossoverValue = 0; % X crossover with Z axis
hAxis.YRuler.SecondCrossoverValue = 0; % Y crossover with Z axis
</pre>
<p><center><figure style="width: 390px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Custom fixed axes crossover location at (0,0,0)" src="https://undocumentedmatlab.com/images/axes_origin_3D3.png" title="Custom fixed axes crossover location at (0,0,0)" width="390" height="230" /><figcaption class="wp-caption-text">Custom fixed axes crossover location at (0,0,0)</figcaption></figure></center></p>
<h3 id="labels">Labels</h3>
<p>Users will encounter the following unexpected behavior (bug?) when using either the documented <b>*AxisLocation</b> or the undocumented <b>FirstCrossoverValue</b> properties: when setting an x-label (using the <i><b>xlabel</b></i> function, or the internal axes properties), the label moves from the center of the axes (as happens when <b>XAxisLocation</b>=&#8217;top&#8217; or &#8216;bottom&#8217;) to the <i>right</i> side of the axes, where the secondary label (e.g., exponent) usually appears, whereas the secondary label is moved to the left side of the axis:<br />
<center><figure style="width: 337px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Unexpected label positions" src="https://undocumentedmatlab.com/images/axes_origin5.png" title="Unexpected label positions" width="337" height="306" /><figcaption class="wp-caption-text">Unexpected label positions</figcaption></figure></center><br />
In such cases, we would expect the labels locations to be reversed, with the main label on the left and the secondary label in its customary location on the right. The exact same situation occurs with the Y labels, where the main label unexpectedly appears at the top and the secondary at the bottom. Hopefully MathWorks will fix this in the next release (it is probably too late to make it into R2016b, but hopefully R2017a). Until then, we can simply switch the strings of the main and secondary label to make them appear at the expected locations:</p>
<pre lang="matlab">
% Switch the Y-axes labels:
ylabel(hAxis, '\times10^{3}');  % display secondary ylabel (x10^3) at top
set(hAxis.YRuler.SecondaryLabel, 'Visible','on', 'String','main y-label');  % main label at bottom
% Switch the X-axes labels:
xlabel(hAxis, '2^{nd} label');  % display secondary xlabel at right
set(hAxis.XRuler.SecondaryLabel, 'Visible','on', 'String','xlabel');  % main label at left
</pre>
<p>As can be seen from the screenshot, there&#8217;s an additional nuisance: the main label appears a bit larger than the axes font size (the secondary label uses the correct font size). This is because by default Matlab uses a 110% font-size for the main axes label, ostensibly to make them stand out. We can modify this default factor using the rulers&#8217; hidden <b>LabelFontSizeMultiplier</b> property (default=1.1). For example:</p>
<pre lang="matlab">
hAxis.YRuler.LabelFontSizeMultiplier = 1;   % use 100% font-size (same as tick labels)
hAxis.XRuler.LabelFontSizeMultiplier = 0.8; % use 80% (smaller than standard) font-size
</pre>
<p>Note: I described the <a href="/articles/customizing-axes-rulers" target="_blank">ruler objects</a> in my first article of the axes series. Feel free to read it for more ideas on customizing the axes rulers.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels">Customizing axes part 5 &#8211; origin crossover and labels</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-tick-labels" rel="bookmark" title="Customizing axes tick labels">Customizing axes tick labels </a> <small>Multiple customizations can be applied to tick labels. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-rulers" rel="bookmark" title="Customizing axes rulers">Customizing axes rulers </a> <small>HG2 axes can be customized in numerous useful ways. This article explains how to customize the rulers. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-2" rel="bookmark" title="Customizing axes part 2">Customizing axes part 2 </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-axes-part-4-additional-properties" rel="bookmark" title="Customizing axes part 4 &#8211; additional properties">Customizing axes part 4 &#8211; additional properties </a> <small>Matlab HG2 axes can be customized in many different ways. This article explains some of the undocumented aspects. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-axes-part-5-origin-crossover-and-labels/feed</wfw:commentRss>
			<slash:comments>13</slash:comments>
		
		
			</item>
		<item>
		<title>Graphic sizing in Matlab R2015b</title>
		<link>https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=graphic-sizing-in-matlab-r2015b</link>
					<comments>https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 20 Jan 2016 18:00:31 +0000</pubDate>
				<category><![CDATA[Figure window]]></category>
		<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6244</guid>

					<description><![CDATA[<p>Matlab release R2015b's new "DPI-aware" nature broke some important functionality. Here's what can be done... </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b">Graphic sizing in Matlab R2015b</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/working-with-non-standard-dpi-displays" rel="bookmark" title="Working with non-standard DPI displays">Working with non-standard DPI displays </a> <small>Matlab uses logical (scaled) pixel positions. With high-DPI displays, this might cause problems, but it is easy to retrieve the physical (unscaled) pixel values. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/couple-of-bugs-and-workarounds" rel="bookmark" title="A couple of internal Matlab bugs and workarounds">A couple of internal Matlab bugs and workarounds </a> <small>A couple of undocumented Matlab bugs have simple workarounds. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I would like to introduce Daniel Dolan of <a href="http://www.sandia.gov" rel="nofollow" target="_blank">Sandia National Laboratories</a>. Dan works on a variety of data analysis projects in Matlab, and is an active lurker on <a href="http://www.mathworks.com/matlabcentral" rel="nofollow" target="_blank">MATLAB Central</a>. Dan has a habit of finding interesting bugs for the Mac version of Matlab. Today he will discuss graphic sizing in Matlab and important changes that occurred in release R2015b.</i><br />
Matlab-generated graphics are often not displayed at their requested size. This problem has been known for some time and has a well-known solution: setting the root object&#8217;s <b>ScreenPixelsPerInch</b> property to the display&#8217;s actual <a href="https://en.wikipedia.org/wiki/Dots_per_inch" rel="nofollow" target="_blank">DPI (dots per inch)</a> value. Release R2015b no longer supports this solution, creating problems for publication graphics and general readability.<br />
<center><figure style="width: 488px" class="wp-caption aligncenter"><a href="/images/DPI_8bpp_976x980.png" rel="nofollow" target="_blank"><img loading="lazy" decoding="async" alt="Physical sizing in R2015a vs. R2015b (click for full-size)" src="https://undocumentedmatlab.com/images/DPI_8bpp_976x980.png" title="Physical sizing in R2015a vs. R2015b (click for full-size)" width="488" height="490" /></a><figcaption class="wp-caption-text">Physical sizing in R2015a vs. R2015b (click for full-size)</figcaption></figure></center><br />
<span id="more-6244"></span></p>
<h3 id="sizing">Physical sizing</h3>
<p>Matlab supports graphic sizing in various physical units: inches, centimeters, and points. For example:</p>
<pre lang="matlab">figure; axes('Box','on', 'Units','inches','Position',[0.3 0.3 4 4]);</pre>
<p>requests to display an axes having square sizes measuring exactly 4&#8243; (101.6 mm) each. It is evident, however, that the displayed axes is smaller than 4&#8243;. The mismatch between requested and physical size depends on the display and operating system &#8212; go ahead, try it on your system. The problem is particularly severe on Mac laptops, presumably even worse for those with Retina displays.<br />
The problem is that Matlab cannot determine pixel size, which varies from one display to the other. Generating a figure spanning a particular number of pixels (e.g., 1024 x 768) is easy, but absolute physical units requires a conversion factor called <b>ScreenPixelsPerInch</b>, which is a <a href="http://www.mathworks.com/help/matlab/ref/root-properties.html" rel="nofollow" target="_blank">root property</a> (see related post on <a href="/articles/getting-default-hg-property-values" target="_blank">setting/getting default graphics property values</a>):</p>
<pre lang="matlab">
DPI = 110;                             % dots per inch for my 27" Apple Cinema Display
set(0,    'ScreenPixelsPerInch',DPI);  % all releases prior to R2015b
set(groot,'ScreenPixelsPerInch',DPI);  % R2014b through R2015a
</pre>
<p>DPI values tend to be higher for laptops, usually in the 120-130 range. Retina displays are supposed to be >300 DPI, but I have not been able to test that myself.<br />
There are several ways to determine the correct DPI setting for a particular display. It may be available in the hardware specifications, and it can be calculated from the diagonal size and the number of pixels. Unfortunately these methods are not always reliable. If you really care about physical sizing, the best approach is to actually calibrate your display. There are tools for doing this at Matlab Central, but it&#8217;s not hard to do manually:</p>
<ul>
<li>Create a figure.</li>
<li>Manually resize the figure to match a convenient width. I often use a piece of US letter paper as 8.5&#8243; guide on the display.</li>
<li>Determine the width of the figure in pixels:
<pre lang="matlab">
set(gcf,'Units','pixels');
pos = get(gcf,'Position');
width = 8.5; % inches
DPI = pos(3) / width;
</pre>
</li>
</ul>
<p>I usually apply the DPI settings in my startup file so that Matlab begins with a calibrated display.</p>
<h3 id="R2015b">What changed in 2015b?</h3>
<p><b>ScreenPixelsPerInch</b> is a read-only property in R2015b, so display calibration no longer works. The following sequence of commands:</p>
<pre lang="matlab">
figure('Units','inches', 'PaperPositionMode','auto', 'Position',[0 0 4 4]);
set(gcf, 'MenuBar','none', 'ToolBar','none', 'DockControls','off', 'NumberTitle','off');
axes('FontUnits','points', 'FontSize',10);
image
</pre>
<p>now renders differently in R2015b than does for a calibrated display in R2015a. Differences between the two outputs are shown in the screenshot at the top of this post. The grid behind the figures was rendered at 8.5&#8243; x 8.5&#8243; inches on my display; if your browser&#8217;s zoom level isn&#8217;t 100%, it may appear larger or smaller.<br />
A side effect of improper graphic sizing is that text is difficult to read &#8212; the uncalibrated axes labels are clearly smaller than 10 points. These examples were rendered on ~110 DPI display. Matlab assumes that Macs use 72 DPI (96 DPI on Windows), so graphics appear at 65% of the request size.<br />
The loss of <b>ScreenPixelsPerInch</b> as an adjustable setting strongly affects anyone using Matlab for publication graphics. Scientific and engineering journals are extremly strict about figure widths. With a calibrated screen, figure appear exactly as they will when printed to a file (usually EPS or PDF). Figures are often made as small as possible to and densely packed to save journal space, and accurate sized display helps the author determine legibility. Displaying accurately sized graphics is very difficult in R2015b, which is unfortunate given the many enhancements in this release.<br />
Developers who create graphical interfaces for other users should also care about this change. A common complaint I get is that text and control labels is too small to easily read. Screen calibration deals with this problem, but this option is no longer available.</p>
<h3 id="workarounds">Where do we go from here?</h3>
<p>I reported the above issues to the Mathworks several months ago. It does not appear as a formal bug, but technical support is aware of the problem. The change is part of the <a href="http://www.mathworks.com/help/matlab/creating_guis/dpi-aware-behavior-in-matlab.html" rel="nofollow" target="_blank">&#8220;DPI aware&#8221; nature of release R2015b</a>. So far I have found no evidence this release is any more aware of pixel size than previous releases, but my experience is limited to non-Retina Macs. I welcome input from users on other operating systems, particularly those with high-resolution displays.<br />
To be fair, correct physical sizing is not an easy across the many platforms that Matlab runs on. Display resolution is particularly tricky when it changes during a Matlab session, such as when computer is connector to projector/television or a laptop is connected to a docking station.<br />
Thankfully, printed graphic sizes are rendered correctly when a figure&#8217;s <b>PaperPositionMode</b> property is <code>'auto'</code>. Many users can (and will) ignore the display problem if they aren&#8217;t dealing with strict size requirements and text legibility isn&#8217;t too bad. Some users may be willing to periodically print publication figures to externally verify sizing, but this breaks the interactive nature of Matlab figures.<br />
A potential work around is the creating of a new figure class that oversizes figures (as needed) to account for a particular display. I started working on such a class, but the problem is more complicated than one might think:</p>
<ul>
<li>Child objects (axes, uicontrols, etc.) also must be resized if they are based on physical units.</li>
<li>Resized objects must be temporarily restored to their original size for printing, and new objects must be tracked whenever they are added.</li>
<li>Figure resolution may need to be changed when moving to different computer systems.</li>
</ul>
<p>These capabilities are quite possible to implement, but this is a complicated solution to problem that was once easy to fix.<br />
Retina displays don&#8217;t suffer as badly as one might think from the DPI mismatch. Even though the display specification may be greater than 200 DPI, OS X and/or Matlab must perform some intermediate size transformations. The effective DPI in R2015a is 110-120 for 13-15&#8243; MacBook Pro laptops (at the default resolution). Objected sized with physical units still appear smaller than they should (~72/110), but not as small as I expected (&lt;72/200).<br />
Effect pixel size can also be changed by switching between different monitor scalings. This isn&#8217;t entirely surprising, but it can lead to some interesting results because Matlab only reads these settings at startup. Changing the display scaling during a session can cause square figures to appear rectangular. Also, the effective DPI changes for setting: I could reach values of ~60-110 DPI on an Apple Cinema Display.<br />
So where does this leave us? Display calibration was always a finicky matter, but at least in principle one could make graphics appear exactly the same size on two different displays. Now it seems that sizing is completely variable between operation systems, displays, and display settings. For publication graphics, there will almost always be a disconnect between figure size on the screen and the printed output; some iteration may be needed to ensure everything looks right in the finished output. For graphical interfaces, font sizes may need to generated in normalized units and then converted to pixels (to avoid resizing).<br />
Physical accuracy may not be important for non-publication figures, but the issue of text legibility remains. Some text objects&#8211;such as axes and tick labels&#8211;can easily be resized because the parent axes automatically adjusts itself as needed. Free floating text objects and uincontrols are much more difficult to deal with. Controls are often sized around the extent of their text label, so changing font sizes may require changes to the control position; adjacent controls may overlap after resizing for text clarity. Normalized units partially solve this problem, but their effect on uicontrols is not always desirable: do you really want push buttons to get larger/smaller when the figure is resized?<br />
Can you think of a better workaround to this problem? If so, then please post a comment below. I will be very happy to hear your ideas, as I&#8217;m sure others who have high resolution displays would as well.<br />
(cross-reference: <a href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/344106" rel="nofollow" target="_blank">CSSM newsgroup post</a>)<br />
<b><u>Addendum Dec 31, 2016</u></b>: Dan Dolan just posted a partial workaround <a href="http://www.mathworks.com/matlabcentral/fileexchange/60953-scaled-figure-class" rel="nofollow" target="_blank">on the MathWorks File Exchange</a>. Also see the related recent article on <a href="/articles/working-with-non-standard-dpi-displays" rel="nofollow" target="_blank">working with non-standard DPI values</a>.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b">Graphic sizing in Matlab R2015b</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles" rel="bookmark" title="Adding dynamic properties to graphic handles">Adding dynamic properties to graphic handles </a> <small>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/working-with-non-standard-dpi-displays" rel="bookmark" title="Working with non-standard DPI displays">Working with non-standard DPI displays </a> <small>Matlab uses logical (scaled) pixel positions. With high-DPI displays, this might cause problems, but it is easy to retrieve the physical (unscaled) pixel values. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/blurred-matlab-figure-window" rel="bookmark" title="Blurred Matlab figure window">Blurred Matlab figure window </a> <small>Matlab figure windows can be blurred using a semi-transparent overlaid window - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/couple-of-bugs-and-workarounds" rel="bookmark" title="A couple of internal Matlab bugs and workarounds">A couple of internal Matlab bugs and workarounds </a> <small>A couple of undocumented Matlab bugs have simple workarounds. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b/feed</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Customizing contour plots</title>
		<link>https://undocumentedmatlab.com/articles/customizing-contour-plots?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-contour-plots</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-contour-plots#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 18 Nov 2015 18:00:55 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[BeanAdapter]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6075</guid>

					<description><![CDATA[<p>Contour labels, lines and fill patches can easily be customized in Matlab HG2. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots">Customizing contour plots</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>Matlab contour labels' color and font can easily be customized. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-histogram-plots" rel="bookmark" title="Customizing histogram plots">Customizing histogram plots </a> <small>Basic bar charts and histogram plots can be customized in important aspects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/hidden-hg2-plot-functionality" rel="bookmark" title="Accessing hidden HG2 plot functionality">Accessing hidden HG2 plot functionality </a> <small>In HG2, some of the plot functionality is hidden in undocumented properties. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>One of my clients asked me last week whether it is possible to access and customize individual contour lines and labels in HG2 (Matlab&#8217;s new graphics system, R2014+). Today&#8217;s post will discuss how this could indeed be done.<br />
<figure style="width: 404px" class="wp-caption alignright"><img loading="lazy" decoding="async" alt="Matlab contour plot" src="https://undocumentedmatlab.com/images/contour.gif" title="Matlab contour plot" width="404" height="307" /><figcaption class="wp-caption-text">Matlab contour plot</figcaption></figure> In HG1 (R2014a and earlier), contour handles were simple <code>hggroup</code> objects that incorporated <code>text</code> and <code>patch</code> child handles. The contour labels, lines and fill patches could easily be accessed via these child handles (contour lines and fills use the same patch object: the lines are simply the patch edges; fills are their faces). The lines could then be customized, the label strings changed, and the patch faces (fills) recolored:</p>
<pre lang='matlab'>
[X,Y,Z] = peaks;
[C,hContour] = contour(X,Y,Z,20, 'ShowText','on');
hChildren = get(hContour, 'Children');
set(hChildren(1), 'String','Yair', 'Color','b');  % 1st text (contour label)
set(hChildren(end), 'EdgeColor',[0,1,1]);         % last patch (contour line)
</pre>
<p>The problem is that in HG2 (R2014b onward), <i><b>contour</b></i> (and its sibling functions, <i><b>contourf</b></i> etc.) return a graphic object that has no accessible children. In other words, <code>hContour.Children</code> returns an empty array:</p>
<pre lang='matlab'>
>> hContour.Children
ans =
  0x0 empty GraphicsPlaceholder array.
>> allchild(hContour)
ans =
  0x0 empty GraphicsPlaceholder array.
>> isempty(hContour.Children)
ans =
     1
</pre>
<p>So how then can we access the internal contour patches and labels?<br />
<span id="more-6075"></span></p>
<h3 id="hg2">HG2&#8217;s contour object&#8217;s hidden properties</h3>
<p>Skipping several fruitless dead-ends, it turns out that in HG2 the text labels, lines and fills are stored in undocumented hidden properties called <b>TextPrims</b>, <b>EdgePrims</b> and (surprise, surprise) <b>FacePrims</b>, which hold corresponding arrays of <code>matlab.graphics.primitive.world.Text</code>, <code>matlab.graphics.primitive.world.LineStrip</code> and <code>matlab.graphics.primitive.world.TriangleStrip</code> object handles (the <i><b>drawnow</b></i> part is also apparently very important, otherwise you might get errors due to the Prim objects not being ready by the time the code is reached):</p>
<pre lang='matlab'>
>> drawnow;  % very important!
>> hContour.TextPrims  % row array of Text objects
ans =
  1x41 Text array:
  Columns 1 through 14
    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text
  Columns 15 through 28
    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text
  Columns 29 through 41
    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text    Text
>> hContour.EdgePrims  % column array of LineStrip objects
ans =
  20x1 LineStrip array:
  ineStrip
  LineStrip
  LineStrip
  ...
>> hContour.FacePrims  % column array of TriangleStrip objects (empty if no fill)
ans =
  0x0 empty TriangleStrip array.
</pre>
<p>We can now access and customize the individual contour lines, labels and fills:</p>
<pre lang='matlab'>
hContour.TextPrims(4).String = 'Dani';
hContour.TextPrims(7).Visible = 'off';
hContour.TextPrims(9).VertexData = single([-1.3; 0.5; 0]);  % Label location in data units
hContour.EdgePrims(2).ColorData = uint8([0;255;255;255]);  % opaque cyan
hContour.EdgePrims(5).Visible = 'off';
</pre>
<p>Note that the <code>LineStrip</code> objects here are the same as those used for the axes Axles, <a target="_blank" href="/articles/customizing-axes-rulers#Axle">which I described</a> a few months ago. Any customization that we could do to the axle <code>LineStrip</code>s can also be applied to contour <code>LineStrip</code>s, and vice versa.<br />
For example, to achieve the appearance of a <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Topographic_map">topographic map</a>, we might want to modify some contour lines to use dotted <b>LineStyle</b> and other lines to appear bold by having larger <b>LineWidth</b>. Similarly, we may wish to hide some labels (by setting their <b>Visible</b> property to &#8216;off&#8217;) and make other labels bold (by setting their <b>Font.Weight</b> property to &#8216;bold&#8217;). There are really numerous customization possibilities here.<br />
Here is a listing of the standard (non-hidden) properties exposed by these objects:</p>
<pre lang='matlab'>
>> get(hContour.TextPrims(1))
        BackgroundColor: []
              ColorData: []
              EdgeColor: []
                   Font: [1x1 matlab.graphics.general.Font]
          FontSmoothing: 'on'
       HandleVisibility: 'on'
                HitTest: 'off'
    HorizontalAlignment: 'center'
            Interpreter: 'none'
                  Layer: 'middle'
              LineStyle: 'solid'
              LineWidth: 1
                 Margin: 1
                 Parent: [1x1 Contour]
          PickableParts: 'visible'
               Rotation: 7.24591082075548
                 String: '-5.1541'
          StringBinding: 'copy'
             VertexData: [3x1 single]
      VerticalAlignment: 'middle'
                Visible: 'on'
>> get(hContour.EdgePrims(1))
          AlignVertexCenters: 'off'
             AmbientStrength: 0.3
                ColorBinding: 'object'
                   ColorData: [4x1 uint8]
                   ColorType: 'truecolor'
             DiffuseStrength: 0.6
            HandleVisibility: 'on'
                     HitTest: 'off'
                       Layer: 'middle'
                     LineCap: 'none'
                    LineJoin: 'round'
                   LineStyle: 'solid'
                   LineWidth: 0.5
               NormalBinding: 'none'
                  NormalData: []
                      Parent: [1x1 Contour]
               PickableParts: 'visible'
    SpecularColorReflectance: 1
            SpecularExponent: 10
            SpecularStrength: 0.9
                   StripData: [1 18]
                     Texture: [0x0 GraphicsPlaceholder]
                  VertexData: [3x17 single]
               VertexIndices: []
                     Visible: 'on'
       WideLineRenderingHint: 'software'
>> get(hContour.FacePrims(1))
             AmbientStrength: 0.3
             BackFaceCulling: 'none'
                ColorBinding: 'object'
                   ColorData: [4x1 uint8]
                   ColorType: 'truecolor'
             DiffuseStrength: 0.6
            HandleVisibility: 'on'
                     HitTest: 'off'
                       Layer: 'middle'
               NormalBinding: 'none'
                  NormalData: []
                      Parent: [1x1 Contour]
               PickableParts: 'visible'
    SpecularColorReflectance: 1
            SpecularExponent: 10
            SpecularStrength: 0.9
                   StripData: [1 4 13 16 33 37 41 44 51 54 61 64 71 74 87 91 94 103]
                     Texture: [0x0 GraphicsPlaceholder]
            TwoSidedLighting: 'off'
                  VertexData: [3x102 single]
               VertexIndices: []
                     Visible: 'on'
</pre>
<p>But how did I know these properties existed? The easiest way in this case would be to use my <a target="_blank" href="/articles/getundoc-get-undocumented-object-properties"><i><b>getundoc</b></i> utility</a>, but we could also use my <a target="_blank" href="/articles/uiinspect"><i><b>uiinspect</b></i> utility</a> or even the plain-ol&#8217; <a target="_blank" href="/articles/accessing-private-object-properties"><i><b>struct</b></i> function</a>.<br />
<i>p.s. &#8211; there&#8217;s an alternative way, using the Java bean adapter that is associated with each Matlab graphics object: <code>java(hContour)</code>. Specifically, this object apparent has the public method <code>browseableChildren(java(hContour))</code> which returns the list of all children (in our case, 41 text labels [bean adapters], 20 lines, and a single object holding a <code>ListOfPointsHighlight</code> that corresponds to the regular hidden <b>SelectionHandle</b> property). However, I generally dislike working with the bean adapters, especially when there&#8217;s a much &#8220;cleaner&#8221; way to get these objects, in this case using the regular <b>EdgePrims</b>, <b>FacePrims</b>, <b>TextPrims</b> and <b>SelectionHandle</b> properties. Readers who are interested in Matlab internals can explore the bean adapters using a combination of my <a target="_blank" href="/articles/getundoc-get-undocumented-object-properties"><b>getundoc</b></a> and <a target="_blank" href="/articles/uiinspect"><b>uiinspect</b></a> utilities.</i><br />
So far for the easy part. Now for some more challenging questions:</p>
<h3 id="color">Customizing the color</h3>
<p>First, can we modify the contour fill to have a semi- (or fully-) transparent fill color? &#8211; indeed we can:</p>
<pre lang='matlab'>
[~, hContour] = contourf(peaks(20), 10);
drawnow;  % this is important, to ensure that FacePrims is ready in the next line!
hFills = hContour.FacePrims;  % array of TriangleStrip objects
[hFills.ColorType] = deal('truecoloralpha');  % default = 'truecolor'
for idx = 1 : numel(hFills)
   hFills(idx).ColorData(4) = 150;   % default=255
end
</pre>
<p><center><figure style="width: 420px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Contour plot in HG2, with and without transparency" src="https://undocumentedmatlab.com/images/hg2-contourf-animated.gif" title="Contour plot in HG2, with and without transparency" width="420" height="300" /><figcaption class="wp-caption-text">Contour plot in HG2, with and without transparency</figcaption></figure></center><br />
Similar transparency effects can also be applied to the <code>LineStrip</code> and <code>Text</code> objects. A discussion of the various combinations of acceptable color properties <a target="_blank" href="/articles/customizing-axes-rulers#Axle">can be found here</a>.</p>
<h3 id="mouse">Mouse clicks</h3>
<p>Next, how can we set a custom context-menu for individual labels and contour lines?<br />
Unfortunately, <code>Text</code>, <code>LineStrip</code> and <code>TriangleStrip</code> objects do not posses a <b>ButtonDownFcn</b> or <b>UIContextMenu</b> property, not even hidden. I tried searching in the internal/undocumented properties, but nothing came up.</p>
<h5 id="mouse1">Mouse click solution #1</h5>
<p>So the next logical step would be to trap the mouse-click event at the contour object level. We cannot simply click the contour and check the clicked object because that would just give us the <code>hContour</code> object handle rather than the individual <code>Text</code> or <code>LineStrip</code>. So the idea would be to set <code>hContour.HitTest='off'</code>, in the hope that the mouse click would be registered on the graphic object directly beneath the mouse cursor, namely the label or contour line. It turns out that the labels&#8217; and lines&#8217; <b>HitTest</b> property is &#8216;off&#8217; by default, so, we also need to set them all to &#8216;on&#8217;:</p>
<pre lang='matlab'>
hContour.HitTest = 'off';
[hContour.TextPrims.HitTest] = deal('on');
[hContour.EdgePrims.HitTest] = deal('on');
[hContour.FacePrims.HitTest] = deal('on');
hContour.ButtonDownFcn = @(h,e)disp(struct(e));
</pre>
<p>This seemed simple enough, but failed spectacularly: it turns out that because <code>hContour.HitTest='off'</code>, mouse clicks are not registered on this objects, and on the other hand we cannot set the <b>ButtonDownFcn</b> on the primitive objects because they don&#8217;t have a <b>ButtonDownFcn</b> property!<br />
Who said life is easy?<br />
One workaround is to set the figure&#8217;s <b>WindowButtonDownFcn</b> property:</p>
<pre lang='matlab'>set(gcf, 'WindowButtonDownFcn', @myMouseClickCallback);</pre>
<p>Now, inside your <code>myMouseClickCallback</code> function you can check the clicked object. We could use the undocumented builtin <a target="_blank" rel="nofollow" href="https://www.mathworks.com/matlabcentral/newsreader/view_thread/239883#613421"><i><b>hittest</b>(hFig)</i> function</a> to see which object was clicked. Alternatively, we could use the callback <code>eventData</code>&#8216;s undocumented <b>HitObject</b>/<b>HitPrimitive</b> properties (this variant does not require the <b>HitTest</b> property modifications above):</p>
<pre lang='matlab'>
function myMouseClickCallback(hFig, eventData)
   hitPrimitive = hittest(hFig);  % undocumented function
   hitObject    = eventData.HitObject;     % undocumented property => returns a Contour object (=hContour)
   hitPrimitive = eventData.HitPrimitive;  % undocumented property => returns a Text or LineStrip object
   hitPoint     = eventData.Point;         % undocumented property => returns [x,y] pixels from figure's bottom-left corner
   if strcmpi(hFig.SelectionType,'alt')  % right-click
      if isa(hitPrimitive, 'matlab.graphics.primitive.world.Text')  % label
         displayTextContextMenu(hitPrimitive, hitPoint)
      elseif isa(hitPrimitive, 'matlab.graphics.primitive.world.LineStrip')  % contour line
         displayLineContextMenu(hitPrimitive, hitPoint)
      elseif isa(hitPrimitive, 'matlab.graphics.primitive.world.TriangleStrip')  % contour fill
         displayFillContextMenu(hitPrimitive, hitPoint)
      else
         ...
      end
   end
end
</pre>
<h5 id="mouse2">Mouse click solution #2</h5>
<p>A totally different solution is to keep the default <code>hContour.HitTest='on'</code> (and the primitives&#8217; as &#8216;off&#8217;) and simply query the contour object&#8217;s <b>ButtonDownFcn</b> callback&#8217;s <code>eventData</code>&#8216;s undocumented <b>Primitive</b> property:</p>
<pre lang='matlab'>hContour.ButtonDownFcn = @myMouseClickCallback;</pre>
<p>And in the callback function:</p>
<pre lang='matlab'>
function myMouseClickCallback(hContour, eventData)
   hitPrimitive = eventData.Primitive;  % undocumented property => returns a Text or LineStrip object
   hitPoint     = eventData.IntersectionPoint;  % [x,y,z] in data units
   hFig = ancestor(hContour, 'figure');
   if strcmpi(hFig.SelectionType,'alt')  % right-click
      if isa(hitPrimitive, 'matlab.graphics.primitive.world.Text')  % label
         displayTextContextMenu(hitPrimitive, hitPoint)
      elseif isa(hitPrimitive, 'matlab.graphics.primitive.world.LineStrip')  % contour line
         displayLineContextMenu(hitPrimitive, hitPoint)
      elseif isa(hitPrimitive, 'matlab.graphics.primitive.world.TriangleStrip')  % contour fill
         displayFillContextMenu(hitPrimitive, hitPoint)
      else
         ...
      end
   end
end
</pre>
<p><a target="_blank" href="/articles/adding-context-menu-to-uitree">This article</a> should be a good start in how to code the <code>displayTextContextMenu</code> etc. functions to display a context menu.</p>
<h3 id="reset">Customizations reset</h3>
<p>Finally, there are apparently numerous things that cause our customized labels and lines to reset to their default appearance: resizing, updating contour properties etc. To update the labels in all these cases in one place, simply listen to the undocumented <a target="_blank" href="/articles/undocumented-hg2-graphics-events"><code>MarkedClean</code> event</a>:</p>
<pre lang='matlab'>addlistener(hContour, 'MarkedClean', @updateLabels);</pre>
<p>Where <code>updateLabels</code> is a function were you set all the new labels.</p>
<h3 id="future">Prediction about forward compatibility</h3>
<p>I am marking this article as &#8220;<a target="_blank" href="/articles/category/presumed-future-risk/high-risk-of-breaking-in-future-versions">High risk of breaking in future Matlab versions</a>&#8220;, not because of the basic functionality (being important enough I don&#8217;t presume it will go away anytime soon) but because of the property names: <b>TextPrims</b>, <b>EdgePrims</b> and <b>FacePrims</b> don&#8217;t seem to be very user-friendly property names. So far MathWorks has been very diligent in making its object properties have meaningful names, and so I assume that when the time comes to expose these properties, they will be renamed (perhaps to <b>TextHandles</b>, <b>EdgeHandles</b> and <b>FaceHandles</b>, or perhaps <b>LabelHandles</b>, <b>LineHandles</b> and <b>FillHandles</b>). For this reason, even if you find out in some future Matlab release that <b>TextPrims</b>, <b>EdgePrims</b> and <b>FacePrims</b> don&#8217;t exist, perhaps they still exist and simply have different names.<br />
<u><b>Addendum November 11, 2017</b></u>: The <b>TextPrims</b>, <b>EdgePrims</b> and <b>FacePrims</b> properties have still not changed their names and functionality. I explained a nice use for them in <a href="/articles/customizing-contour-plots-part2" target="_blank">a followup post</a>, explaining how we can modify the contour labels to have different font sizes and the same colors as their corresponding contour lines.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots">Customizing contour plots</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>Matlab contour labels' color and font can easily be customized. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2" rel="bookmark" title="Customizing contour plots part 2">Customizing contour plots part 2 </a> <small>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/customizing-histogram-plots" rel="bookmark" title="Customizing histogram plots">Customizing histogram plots </a> <small>Basic bar charts and histogram plots can be customized in important aspects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/hidden-hg2-plot-functionality" rel="bookmark" title="Accessing hidden HG2 plot functionality">Accessing hidden HG2 plot functionality </a> <small>In HG2, some of the plot functionality is hidden in undocumented properties. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-contour-plots/feed</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
	</channel>
</rss>
