<?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>HG2 &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/hg2/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Wed, 13 Mar 2019 11:05:14 +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>Undocumented plot marker types</title>
		<link>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=undocumented-plot-marker-types</link>
					<comments>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 13 Mar 2019 11:05:14 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Hidden property]]></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[Internal component]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=8539</guid>

					<description><![CDATA[<p>Undocumented plot marker styles can easily be accesses using a hidden plot-line property. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types">Undocumented plot marker types</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/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</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/undocumented-scatter-plot-jitter" rel="bookmark" title="Undocumented scatter plot jitter">Undocumented scatter plot jitter </a> <small>Matlab's scatter plot can automatically jitter data to enable better visualization of distribution density. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I wanted to take a break from my miniseries on the Matlab toolstrip to describe a nice little undocumented aspect of plot line markers. Plot line marker types have remained essentially unchanged in user-facing functionality for the past two+ decades, allowing the well-known marker types (.,+,o,^ etc.). Internally, lots of things changed in the graphics engine, particularly in the <a href="https://undocumentedmatlab.com/articles/hg2-update" target="_blank">transition to HG2</a> in R2014b and the <a href="https://blogs.mathworks.com/graphics/2015/11/10/memory-consumption/#comment-465" rel="nofollow" target="_blank">implementation of markers using OpenGL primitives</a>. I suspect that during the massive amount of development work that was done at that time, important functionality improvements that were implemented in the engine were forgotten and did not percolate all the way up to the user-facing functions. I highlighted a few of these in the past, for example transparency and color gradient for <a href="https://undocumentedmatlab.com/articles/plot-line-transparency-and-color-gradient" target="_blank">plot lines</a> and <a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" target="_blank">markers</a>, or <a href="https://undocumentedmatlab.com/articles/hidden-hg2-plot-functionality" target="_blank">various aspects of contour plots</a>.<br />
Fortunately, Matlab usually exposes the internal objects that we can customize and which enable these extra features, in hidden properties of the top-level graphics handle. For example, the standard Matlab plot-line handle has a hidden property called <b>MarkerHandle</b> that we can access. This returns an internal object that enables <a href="https://undocumentedmatlab.com/articles/plot-markers-transparency-and-color-gradient" target="_blank">marker transparency and color gradients</a>. We can also use this object to set the marker style to a couple of formats that are not available in the top-level object:</p>
<pre lang="matlab">
>> x=1:10; y=10*x; hLine=plot(x,y,'o-'); box off; drawnow;
>> hLine.MarkerEdgeColor = 'r';
>> set(hLine, 'Marker')'  % top-level marker styles
ans =
  1×14 cell array
    {'+'} {'o'} {'*'} {'.'} {'x'} {'square'} {'diamond'} {'v'} {'^'} {'>'} {'<'} {'pentagram'} {'hexagram'} {'none'}
>> set(hLine.MarkerHandle, 'Style')'  % low-level marker styles
ans =
  1×16 cell array
    {'plus'} {'circle'} {'asterisk'} {'point'} {'x'} {'square'} {'diamond'} {'downtriangle'} {'triangle'} {'righttriangle'} {'lefttriangle'} {'pentagram'} {'hexagram'} {'vbar'} {'hbar'} {'none'}
</pre>
<p>We see that the top-level marker styles directly correspond to the low-level styles, except for the low-level &#8216;vbar&#8217; and &#8216;hbar&#8217; styles. Perhaps the developers forgot to add these two styles to the top-level object in the enormous upheaval of HG2. Luckily, we can set the hbar/vbar styles directly, using the line&#8217;s <b>MarkerHandle</b> property:</p>
<pre lang="matlab">
hLine.MarkerHandle.Style = 'hbar';
set(hLine.MarkerHandle, 'Style','hbar');  % alternative
</pre>
<p><center><figure style="width: 213px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/plot_hbar.png" alt="hLine.MarkerHandle.Style='hbar'" title="hLine.MarkerHandle.Style='hbar'" width="213" height="155" /><figcaption class="wp-caption-text">hLine.MarkerHandle.Style='hbar'</figcaption></figure> <figure style="width: 213px" class="wp-caption aligncenter"><img decoding="async" src="https://undocumentedmatlab.com/images/plot_vbar.png" alt="hLine.MarkerHandle.Style='vbar'" title="hLine.MarkerHandle.Style='vbar'" width="213" height="155" /><figcaption class="wp-caption-text">hLine.MarkerHandle.Style='vbar'</figcaption></figure></center></p>
<h3 id="USA">USA visit</h3>
<p>I will be travelling in the US in May/June 2019. Please let me know (altmany at gmail) if you would like to schedule a meeting or onsite visit for consulting/training, or perhaps just to explore the possibility of my professional assistance to your Matlab programming needs.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/undocumented-plot-marker-types">Undocumented plot marker types</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/types-of-undocumented-matlab-aspects" rel="bookmark" title="Types of undocumented Matlab aspects">Types of undocumented Matlab aspects </a> <small>This article lists the different types of undocumented/unsupported/hidden aspects in Matlab...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/undocumented-scatter-plot-behavior" rel="bookmark" title="Undocumented scatter plot behavior">Undocumented scatter plot behavior </a> <small>The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific point as it returns with 100 or less points....</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/undocumented-scatter-plot-jitter" rel="bookmark" title="Undocumented scatter plot jitter">Undocumented scatter plot jitter </a> <small>Matlab's scatter plot can automatically jitter data to enable better visualization of distribution density. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/undocumented-plot-marker-types/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Auto-scale image colors</title>
		<link>https://undocumentedmatlab.com/articles/auto-scale-image-colors?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=auto-scale-image-colors</link>
					<comments>https://undocumentedmatlab.com/articles/auto-scale-image-colors#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 21 Feb 2018 18:06:23 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Listeners]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[Listener]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=7334</guid>

					<description><![CDATA[<p>Images can be automatically color-scaled for maximum resolution, using the undocumented MarkedClean  event. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/auto-scale-image-colors">Auto-scale image colors</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/image-easter-egg" rel="bookmark" title="Image Easter egg">Image Easter egg </a> <small>The default image presented by Matlab's image function has a very interesting undocumented story....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/auto-completion-widget" rel="bookmark" title="Auto-completion widget">Auto-completion widget </a> <small>Matlab includes a variety of undocumented internal controls that can be used for an auto-completion component. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/persisting-transparent-colors-in-hg2" rel="bookmark" title="Persisting transparent colors in HG2">Persisting transparent colors in HG2 </a> <small>We can set semi- and fully-transparent colors in HG2 for multiple graphic objects, but making these settings stick is non-trivial. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitable-cell-colors" rel="bookmark" title="Uitable cell colors">Uitable cell colors </a> <small>A few Java-based customizations can transform a plain-looking data table into a lively colored one. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>I deal extensively in image processing in one of my consulting projects. The images are such that most of the interesting features are found in the central portion of the image. However, the margins of the image contain z-values that, while not interesting from an operational point-of-view, cause the displayed image&#8217;s color-limits (axes <b>CLim</b> property) to go wild. An image is worth a thousand words, so check the following raw image (courtesy of Flightware, Inc.), displayed by the following simple script:</p>
<pre lang="matlab">hImage = imagesc(imageData); colormap(gray); colorbar;</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" src="https://undocumentedmatlab.com/images/baseline2_1.png" alt="Raw image with default Matlab CLim" title="Raw image with default Matlab CLim" width="400" height="299" /><figcaption class="wp-caption-text">Raw image with default Matlab CLim</figcaption></figure></center></p>
<h3 id="rescale">Rescaling the axes color-limits</h3>
<p>As you can see, this image is pretty useless for human-eye analysis. The reason is that while all of the interesting features in the central portion of the image have a z-value of ~-6, the few pixels in the margins that have a z-value of 350+ screw up the color limits and ruin the perceptual resolution (image contrast). We could of course start to guess (or <i><b>histogram</b></i> the z-values) to get the interesting color-limit range, and then manually set <code>hAxes.CLim</code> to get a much more usable image:</p>
<pre lang="matlab">hAxes = hImage.Parent; hAxes.CLim = [-7.5,-6];</pre>
<p><center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/static_1.png" alt="Raw image with a custom CLim" title="Raw image with a custom CLim" width="400" height="299" /><figcaption class="wp-caption-text">Raw image with a custom CLim</figcaption></figure></center></p>
<h3 id="autoscale">Auto-scaling the axes color-limits</h3>
<p>Since the z-values range and distribution changes between different images, it would be better to automatically scale the axes color-limits based on an analysis of the image. A very simple technique for doing this is to take the 5%,95% or 10%,90% percentiles of the data, clamping all outlier data pixels to the extreme colors. If you have the Stats Toolbox you can use the <i><b>prctile</b></i> function for this, but if not (or even if you do), here&#8217;s a very fast alternative that automatically scales the axes color limits based on the specified threshold (a fraction between 0-0.49):<br />
<span id="more-7334"></span></p>
<pre lang="matlab">
% Rescale axes CLim based on displayed image portion's CData
function rescaleAxesClim(hImage, threshold)
    % Get the displayed image portion's CData
    CData = hImage.CData;
    hAxes = hImage.Parent;
    XLim = fix(hAxes.XLim);
    YLim = fix(hAxes.YLim);
    rows = min(max(min(YLim):max(YLim),1),size(CData,1)); % visible portion
    cols = min(max(min(XLim):max(XLim),1),size(CData,2)); % visible portion
    CData = CData(unique(rows),unique(cols));
    CData = CData(:);  % it's easier to work with a 1d array
    % Find the CLims from this displayed portion's CData
    CData = sort(CData(~isnan(CData)));  % or use the Stat Toolbox's prctile()
    thresholdVals = [threshold, 1-threshold];
    thresholdIdxs = fix(numel(CData) .* thresholdVals);
    CLim = CData(thresholdIdxs);
    % Update the axes
    hAxes.CLim = CLim;
end
</pre>
<p>Note that a threshold of 0 uses the full color range, resulting in no <b>CLim</b> rescaling at all. At the other extreme, a threshold approaching 0.5 reduces the color-range to a single value, basically reducing the image to an unusable B/W (rather than grayscale) image. Different images might require different thresholds for optimal contrast. I believe that a good starting point for the threshold is a value of 0.10, which corresponds to the 10-90% range of <b>CData</b> values.</p>
<h3 id="dynamic">Dynamic auto-scaling of axes color-limits</h3>
<p>This is very nice for the initial image display, but if we zoom-in, or pan a sub-image around, or update the image in some way, we would need to repeat calling this <i>rescaleAxesClim()</i> function every time the displayed image portion changes, otherwise we might still get unusable images. For example, if we zoom into the image above, we will see that the color-limits that were useful for the full image are much less useful on the local sub-image scale. The first (left) image uses the static custom color limits [-7.5,-6] above (i.e., simply zooming-in on that image, without modifying <b>CLim</b> again); the second (right) image is the result of repeating the call to <i>rescaleAxesClim()</i>, which improves the image contrast:<br />
<center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/static_4.png" alt="Zoomed-in image with a custom static CLim" title="Zoomed-in image with a custom static CLim" width="400" height="299" /><figcaption class="wp-caption-text">Zoomed-in image with a custom static CLim</figcaption></figure> <figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/dynamic_4.png" alt="Zoomed-in image with a re-applied custom CLim" title="Zoomed-in image with a re-applied custom CLim" width="400" height="299" /><figcaption class="wp-caption-text">Zoomed-in image with a re-applied custom CLim</figcaption></figure> </center><br />
We could in theory attach the <i>rescaleAxesClim()</i> function as a callback to the <i><b>zoom</b></i> and <i><b>pan</b></i> functions (that provide such callback hooks). However, we would still need to remember to manually call this function whenever we modify the image or its containing axes programmatically.<br />
A much simpler way is to attach our <i>rescaleAxesClim()</i> function as a callback to the image&#8217;s undocumented <a href="/articles/undocumented-hg2-graphics-events" target="_blank"><b>MarkedClean</b> event</a>:</p>
<pre lang="matlab">
% Instrument image: add a listener callback to rescale upon any image update
addlistener(hImage, 'MarkedClean', @(h,e)rescaleAxesClim(hImage,threshold));
</pre>
<p>In order to avoid callback recursion (potentially caused by modifying the axes <b>CLim</b> within the callback), we need to add a bit of code to the callback that prevents recursion/reentrancy (<a href="/articles/controlling-callback-re-entrancy" target="_blank">details</a>). Here&#8217;s one simple way to do this:</p>
<pre lang="matlab">
% Rescale axes CLim based on displayed image portion's CData
function rescaleAxesClim(hImage, threshold)
    % Check for callback reentrancy
    inCallback = getappdata(hImage, 'inCallback');
    if ~isempty(inCallback), return, end
    try
        setappdata(hImage, 'inCallback',1);  % prevent reentrancy
        % Get the displayed image portion's CData
        ...  (copied from above)
        % Update the axes
        hAx.CLim = CLim;
        drawnow; pause(0.001);  % finish all graphic updates before proceeding
    catch
    end
    setappdata(hImage, 'inCallback',[]);  % reenable this callback
end
</pre>
<p>The result of this dynamic automatic color-scaling can be seen below:<br />
<center><figure style="width: 400px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://undocumentedmatlab.com/images/dynamic_animated.gif" alt="Zoomed-in image with dynamic CLim" title="Zoomed-in image with dynamic CLim" width="400" height="299" /><figcaption class="wp-caption-text">Zoomed-in image with dynamic CLim</figcaption></figure></center></p>
<h3 id="autoScaleImageCLim">autoScaleImageCLim utility</h3>
<p>I have created a small utility called <i><b>autoScaleImageCLim</b></i>, which includes all the above, and automatically sets the specified input image(s) to use auto color scaling. Feel free to download this utility from <a href="https://www.mathworks.com/matlabcentral/fileexchange/66148-autoscaleimageclim" rel="nofollow" target="_blank">the Matlab File Exchange</a>. Here are a few usage examples:</p>
<pre lang="matlab">
autoScaleImageCLim()           % auto-scale the current axes' image
autoScaleImageCLim(hImage,5)   % auto-scale image using 5%-95% CData limits
autoScaleImageCLim(hImage,.07) % auto-scale image using 7%-93% CData limits
</pre>
<p>(note that the <code>hImage</code> input parameter can be an array of image handles)<br />
Hopefully one day the so-useful <b>MarkedClean</b> event will become a documented and fully-supported event for all HG objects in Matlab, so that we won&#8217;t need to worry that it might not be supported by some future Matlab release&#8230;</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/auto-scale-image-colors">Auto-scale image colors</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/image-easter-egg" rel="bookmark" title="Image Easter egg">Image Easter egg </a> <small>The default image presented by Matlab's image function has a very interesting undocumented story....</small></li>
<li><a href="https://undocumentedmatlab.com/articles/auto-completion-widget" rel="bookmark" title="Auto-completion widget">Auto-completion widget </a> <small>Matlab includes a variety of undocumented internal controls that can be used for an auto-completion component. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/persisting-transparent-colors-in-hg2" rel="bookmark" title="Persisting transparent colors in HG2">Persisting transparent colors in HG2 </a> <small>We can set semi- and fully-transparent colors in HG2 for multiple graphic objects, but making these settings stick is non-trivial. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/uitable-cell-colors" rel="bookmark" title="Uitable cell colors">Uitable cell colors </a> <small>A few Java-based customizations can transform a plain-looking data table into a lively colored one. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/auto-scale-image-colors/feed</wfw:commentRss>
			<slash:comments>1</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>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>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>Customizing contour plots part 2</title>
		<link>https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=customizing-contour-plots-part-2</link>
					<comments>https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 09 Mar 2016 18:00:49 +0000</pubDate>
				<category><![CDATA[Hidden property]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Medium risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[Undocumented property]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6304</guid>

					<description><![CDATA[<p>The contour lines of 3D Matlab plot can be customized in many different ways. This is the 2nd article on this issue. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2">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-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" 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-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-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A few months ago <a href="/articles/customizing-contour-plots" target="_blank">I discussed</a> various undocumented manners by which we can customize Matlab contour plots. A short while ago I receive an email from a blog reader (thanks Frank!) alerting me to another interesting way by which we can customize such plots, using the contour handle&#8217;s hidden <b>ContourZLevel</b> property. In today&#8217;s post I will explain how we can use this property and expand the discussion with some visualization interactivity.</p>
<h3 id="ContourZLevel">The ContourZLevel property</h3>
<p>The contour handle&#8217;s <b>ContourZLevel</b> property is a hidden property. This means that, just like all other hidden properties, it is accessible if we just happen to know its name (which is easy using my <a href="/articles/getundoc-get-undocumented-object-properties" rel="nofollow" target="_blank"><i><b>getundoc</b></i> utility</a>). This property sets the Z level at which the contour lines are drawn.<br />
For example, by default the <i><b>meshc</b></i> function sets <b>ContourZLevel</b>&#8216;s value to the bottom of the 3D display (in other words, to the axes&#8217; <b>ZLim</b>(1) value). This is done within the <i>mesh.m</i> function:<br />
<center><figure style="width: 350px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Standard Matlab meshc output (contour at bottom)" src="https://undocumentedmatlab.com/images/meshc1.png" title="Standard Matlab meshc output (contour at bottom)" width="350" height="255" /><figcaption class="wp-caption-text">Standard Matlab meshc output (contour at bottom)</figcaption></figure></center><br />
We can, however, modify the contour&#8217;s level value to any other Z location:<br />
<span id="more-6304"></span></p>
<pre lang="matlab">
% create a mesh and contour plot
handles = meshc(peaks);
% handles is a 2-element array of handles: the surface plot and the contours
hContour = handles(2); % get the handle to the contour lines
hContour.ContourZLevel = 4.5; % set the contour's Z position (default: hAxes.ZLim(1)=-10)
% We can also customize other aspects of the contour lines, for example:
hContour.LineWidth = 2; % set the contour lines' width (default: 0.5)
</pre>
<p><center><figure style="width: 344px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Customized Matlab meshc output" src="https://undocumentedmatlab.com/images/meshc2.png" title="Customized Matlab meshc output" width="344" height="255" /><figcaption class="wp-caption-text">Customized Matlab meshc output</figcaption></figure></center></p>
<h3 id="interactivity">Adding some visualization interactivity</h3>
<p>Now let&#8217;s add some fun interactivity using a vertical slider to control the contour&#8217;s height (Z level). Matlab&#8217;s slider uicontrol is really just an ugly scrollbar, so we&#8217;ll use a Java <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/slider.html" rel="nofollow" target="_blank">JSlider</a> instead:</p>
<pre lang="matlab">
% Add a controlling slider to the figure
jSlider = javaObjectEDT(javax.swing.JSlider);
jSlider.setOrientation(jSlider.VERTICAL);
jSlider.setPaintTicks(true);
jSlider.setMajorTickSpacing(20);
jSlider.setMinorTickSpacing(5);
jSlider.setBackground(java.awt.Color.white);
[hjSlider, hContainer] = javacomponent(jSlider, [10,10,30,120], gcf);
% Set the slider's action callback
hAxes = hContour.Parent;  % handle to containing axes
zmin = hAxes.ZLim(1);
zmax = hAxes.ZLim(2);
zrange = zmax - zmin;
cbFunc = @(hSlider,evtData) set(hContour,'ContourZLevel',hSlider.getValue/100*zrange+zmin);
hjSlider.StateChangedCallback = cbFunc;  % set the callback for slider action events
cbFunc(hjSlider,[]);  % evaluate the callback to synchronize the initial display
</pre>
<p><center><figure style="width: 392px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Interactive contour height" src="https://undocumentedmatlab.com/images/meshc_animated.gif" title="Interactive contour height" width="392" height="256" /><figcaption class="wp-caption-text">Interactive contour height</figcaption></figure></center></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2">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-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" 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-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-figure-toolbar-background" rel="bookmark" title="Customizing figure toolbar background">Customizing figure toolbar background </a> <small>Setting the figure toolbar's background color can easily be done using just a tiny bit of Java magic powder. This article explains how. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/customizing-contour-plots-part-2/feed</wfw:commentRss>
			<slash:comments>5</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>
		<item>
		<title>Adding dynamic properties to graphic handles</title>
		<link>https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=adding-dynamic-properties-to-graphic-handles</link>
					<comments>https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 16 Sep 2015 17:26:44 +0000</pubDate>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Stock Matlab function]]></category>
		<category><![CDATA[UI controls]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Undocumented function]]></category>
		<category><![CDATA[Donn Shull]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<category><![CDATA[schema.prop]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6006</guid>

					<description><![CDATA[<p>It is easy and very useful to attach dynamic properties to Matlab graphics objects in run-time. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles">Adding dynamic properties to graphic handles</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-custom-properties-to-gui-objects" rel="bookmark" title="Adding custom properties to GUI objects">Adding custom properties to GUI objects </a> <small>It is very easy to add custom user-defined properties and methods to GUI handles and Java references in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b" rel="bookmark" title="Graphic sizing in Matlab R2015b">Graphic sizing in Matlab R2015b </a> <small>Matlab release R2015b's new "DPI-aware" nature broke some important functionality. Here's what can be done... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>A client recently asked me to extend one of Matlab&#8217;s built-in graphic containers (<a target="_blank" href="/articles/matlab-layout-managers-uicontainer-and-relatives"><i><b>uiflowcontainer</b></i></a> in this specific case) with automatic scrollbars that would enable the container to act as a scroll-panel. The basic idea would be to dynamically monitor the container&#8217;s contents and when it is determined that they overflow the container&#8217;s boundaries, then attach horizontal/vertical scrollbars to enable scrolling the contents into view:<br />
<center><figure style="width: 350px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Scrollable Matlab container" src="https://undocumentedmatlab.com/images/uiflowcontainer_scroll.gif" title="Scrollable Matlab container" width="350" height="260" /><figcaption class="wp-caption-text">Scrollable Matlab container</figcaption></figure></center><br />
This may sound simple, but there are actually quite a few undocumented hacks that make this possible, including listening to <code>ObjectChildAdded/ObjectChildRemoved</code> events, location/size/visibility events, layout changes etc. Maybe I&#8217;ll blog about it in some future article.<br />
Today&#8217;s post is focused on a specific aspect of this project, attaching dynamic properties to the builtin <i><b>uiflowcontainer</b></i>, that would enable users to modify the container&#8217;s properties directly, as well as control aspects of the scrolling using the new properties: handles to the parent container, as well as the horizontal and vertical scrollbars, and even a new <i>refresh()</i> method.<br />
<span id="more-6006"></span><br />
The &#8220;textbook&#8221; approach to this would naturally be to create a new class that extends (inherits) <i><b>uiflowcontainer</b></i> and includes these new properties and methods. Unfortunately, for some reason that escapes my understanding, MathWorks saw fit to make all of its end-use graphic object classes <code>Sealed</code>, such that they cannot be extended by users. I did ask for this to be changed long ago, but the powers that be apparently decided that it&#8217;s better this way.<br />
So the fallback would be to create our own dedicated class having all the new properties as well as those of the original container, and ensure that all the property values are synchronized in both directions. This is probably achievable, if you have a spare few days and a masochistic state of mind. Being the lazy bum and authority-rebel that I am, I decided to take an alternate approach that would simply add my new properties to the built-in container handle. The secret lies in the undocumented function <i><b>schema.prop</b></i> (for HG1, R2014a and older) and the fully-documented <i><b>addprop</b></i> function (for HG2, R2014b and newer).<br />
In the examples below I use a panel, but this mechanism works equally well on any Matlab HG object: axes, lines, uicontrols, figures, etc.</p>
<h3 id="HG2">HG2 &#8211; addprop function</h3>
<p>The <i><b>addprop</b></i> function is actually a public method of the <code>dynamicprops</code> class. Both the <code>dynamicprops</code> class as well as its <i><b>addprop</b></i> function are <a target="_blank" rel="nofollow" href="http://www.mathworks.com/help/matlab/ref/dynamicprops.addprop.html">fully documented</a>. What is NOT documented, as far as I could tell, is that all of Matlab&#8217;s builtin handle graphics objects indirectly inherit <code>dynamicprops</code>, via <code>matlab.graphics.Graphics</code>, which is a high-level superclass for all HG objects. The bottom line is that we can dynamically add run-time properties to any HG object, without affecting any other object. In other words, the new properties will only be added to the handles that we specifically request, and not to any others. This suits me just fine:</p>
<pre lang='matlab'>
hProp = addprop(hPanel, 'hHorizontalScrollBar');
hPanel.hHorizontalScrollBar = hMyScrollbar;
hProp.SetAccess = 'private';  % make this property read-only
</pre>
<p>The new property <code>hHorizontalScrollBar</code> is now added to the <code>hPanel</code> handle, and can be accessed just like any other read-only property. For example:</p>
<div class="wp_syntax">
<div class="code">
<pre class="matlab" style="font-family:monospace;">&gt;&gt; <span style="color: #0000FF;">get</span><span style="color: #080;">(</span>hPanel, <span style="color:#A020F0;">'hHorizontalScrollBar'</span><span style="color: #080;">)</span>
<span style="color: #0000FF;">ans</span> =
    JavaWrapper
&gt;&gt; hPanel.<span style="">hHorizontalScrollBar</span>
<span style="color: #0000FF;">ans</span> =
    JavaWrapper
&gt;&gt; hPanel.<span style="">hHorizontalScrollBar</span> = <span style="color: #33f;">123</span>
<span style="color: #FF0000;">You cannot set the read-only property 'hHorizontalScrollBar' of UIFlowContainer.</span></pre>
</div>
</div>
<p>Adding new methods is more tricky, since we do not have a corresponding <i>addmethod</i> function. The trick I used was to create a new property having the requested new method&#8217;s name, and set its read-only value to a handle of the requested function. For example:</p>
<pre lang='matlab'>
hProp = addprop(hPanel, 'refresh');
hPanel.refresh = @myRefreshFunc;
hProp.SetAccess = 'private';  % make this property read-only
</pre>
<p>We can then invoke the new <i>refresh</i> &#8220;method&#8221; using the familiar dot-notation:</p>
<pre lang='matlab'>hPanel.refresh();</pre>
<p>Note: if you ever need to modify the initial value in your code, you should revert the property&#8217;s <b>SetAccess</b> meta-property to <code>'public'</code> before Matlab will enable you to modify the value:</p>
<pre lang='matlab'>
try
    % This will raise an exception if the property already exists
    hProp = addprop(hPanel, propName);
catch
    % Property already exists - find it and set its access to public
    hProp = findprop(hPanel, propName);
    hProp.SetAccess = 'public';
end
hPanel.(propName) = newValue;
</pre>
<h3 id="HG1">HG1 &#8211; schema.prop function</h3>
<p>In HG1 (R2014a and earlier), we can use the undocumented <i><b>schema.prop</b></i> function to add a new property to any HG handle (which is a numeric value in HG1). Donn Shull <a target="_blank" href="/articles/udd-properties">wrote about <i><b>schema.prop</b></i></a> back in 2011, as part of his series of articles on UDD (Unified Data Dictionary, MCOS&#8217;s precursor). In fact, <i><b>schema.prop</b></i> is so useful that it has its own <a target="_blank" href="/articles/tag/schemaprop">blog tag here</a> and appears in no less than 15 separate articles (excluding today). With HG2&#8217;s debut 2 years ago, MathWorks tried very hard to rid the Matlab code corpus of all the legacy schema-based, replacing most major functionalities with MCOS-based HG2 code. But so far it has proven impossible to get rid of schema completely, and so schema code is still used extensively in Matlab to this day (R2015b). Search your Matlab path for &#8220;schema.prop&#8221; and see for yourself.<br />
Anyway, the basic syntax is this:</p>
<pre lang='matlab'>hProp = schema.prop(hPanel, propName, 'mxArray');</pre>
<p>The <code>'mxArray'</code> specifies that the new property can accept any data type. We can limit the property to only accept certain types of data by specifying a less-generic data type, among those recognized by UDD (<a target="_blank" href="/articles/udd-properties#DataType">details</a>).<br />
Note that the meta-properties of the returned <code>hProp</code> are somewhat different from those of HG2&#8217;s <code>hProp</code>. Taking this into account, here is a unified function that adds/updates a new property (with optional initial value) to any HG1/HG2 object:</p>
<pre lang='matlab'>
function addProp(hObject, propName, initialValue, isReadOnly)
    try
        hProp = addprop(hObject, propName);  % HG2
    catch
        try
            hProp = schema.prop(hObject, propName, 'mxArray');  % HG1
        catch
            hProp = findprop(hObject, propName);
        end
    end
    if nargin > 2
        try
            hProp.SetAccess = 'public';  % HG2
        catch
            hProp.AccessFlags.PublicSet = 'on';  % HG1
        end
        hObject.(propName) = initialValue;
    end
    if nargin > 3 && isReadOnly
        try
            % Set the property as read-only
            hProp.SetAccess = 'private';  % HG2
        catch
            hProp.AccessFlags.PublicSet = 'off';  % HG1
        end
    end
end
</pre>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles">Adding dynamic properties to graphic handles</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-custom-properties-to-gui-objects" rel="bookmark" title="Adding custom properties to GUI objects">Adding custom properties to GUI objects </a> <small>It is very easy to add custom user-defined properties and methods to GUI handles and Java references in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/performance-accessing-handle-properties" rel="bookmark" title="Performance: accessing handle properties">Performance: accessing handle properties </a> <small>Handle object property access (get/set) performance can be significantly improved using dot-notation. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/graphic-sizing-in-matlab-r2015b" rel="bookmark" title="Graphic sizing in Matlab R2015b">Graphic sizing in Matlab R2015b </a> <small>Matlab release R2015b's new "DPI-aware" nature broke some important functionality. Here's what can be done... ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/udd-properties" rel="bookmark" title="UDD Properties">UDD Properties </a> <small>UDD provides a very convenient way to add customizable properties to existing Matlab object handles...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/adding-dynamic-properties-to-graphic-handles/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Persisting transparent colors in HG2</title>
		<link>https://undocumentedmatlab.com/articles/persisting-transparent-colors-in-hg2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=persisting-transparent-colors-in-hg2</link>
					<comments>https://undocumentedmatlab.com/articles/persisting-transparent-colors-in-hg2#comments</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Wed, 03 Jun 2015 18:00:49 +0000</pubDate>
				<category><![CDATA[Handle graphics]]></category>
		<category><![CDATA[Low risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[HG2]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=5820</guid>

					<description><![CDATA[<p>We can set semi- and fully-transparent colors in HG2 for multiple graphic objects, but making these settings stick is non-trivial. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/persisting-transparent-colors-in-hg2">Persisting transparent colors in HG2</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/transparent-legend" rel="bookmark" title="Transparent legend">Transparent legend </a> <small>Matlab chart legends are opaque be default but can be made semi- or fully transparent. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-uipanels" rel="bookmark" title="Transparent uipanels">Transparent uipanels </a> <small>Matlab uipanels can be made transparent, for very useful effects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-matlab-figure-window" rel="bookmark" title="Transparent Matlab figure window">Transparent Matlab figure window </a> <small>Matlab figure windows can be made fully or partially transparent/translucent or blurred - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-labels" rel="bookmark" title="Transparent labels">Transparent labels </a> <small>Matlab labels can be set to a transparent background as well as padding. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p>Several months ago, I showed how we can set semi- and fully-transparent colors in HG2 (Matlab&#8217;s new graphics engine, starting in R2014b) for multiple graphic objects, including <a target="_blank" href="/articles/plot-line-transparency-and-color-gradient">plot lines</a>, <a target="_blank" href="/articles/plot-markers-transparency-and-color-gradient">plot markers</a>, and <a target="_blank" href="/articles/plot-markers-transparency-and-color-gradient#comment-338635">area charts</a>:</p>
<pre lang='matlab'>
hLine = plot([0,150], [-0.5,0.5], 'r');
box off; hold on;
ydata = sin(0:0.1:15);
hArea = area(ydata);
drawnow; pause(0.05);  % this is important!
hArea.Face.ColorType = 'truecoloralpha';
hArea.Face.ColorData(4) = 40;  % 40/255 = 0.16 opacity = 84% transparent
</pre>
<p>Unfortunately, these settings are automatically overridden by Matlab when the figure is printed, saved, or exported:</p>
<pre lang='matlab'>
% These commands result in an opaque (non-transparent) plot
print(gcf);
saveas(gcf, 'plot.png');
</pre>
<p><center><figure style="width: 350px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" alt="Transparent area plot (ok)" src="https://undocumentedmatlab.com/images/transparency1.gif" title="Transparent area plot (ok)" width="160" height="125" /> &nbsp; <img loading="lazy" decoding="async" alt="Opaque area plot (not ok)" src="https://undocumentedmatlab.com/images/transparency0.gif" title="Opaque area plot (not ok)" width="160" height="125" /><figcaption class="wp-caption-text">Area plot: transparent (ok) and opaque (not ok)</figcaption></figure></center><br />
<span id="more-5820"></span><br />
In some cases, the settings are lost even when the figure or axes is resized, or properties (e.g., <b>Box</b>) are changed. This is evident, for example, when the <code>hLine</code> plot line is not drawn, only the area plot.<br />
The solution of <a target="_blank" href="/articles/plot-markers-transparency-and-color-gradient#comment-339759">one blog reader here</a> was to simply set the undocumented color transparency settings at the very end of the graphics set-up. However, as noted, this still does not answer the need to preserve the color settings when the figure is printed, saved, exported, or resized, or when axes properties change.<br />
Another reader, Richard de Garis of <a target="_blank" rel="nofollow" href="http://collinscap.com/index.html">Collins Capital</a>, found an undocumented feature that seems to solve the problem for good. It turns out that the solution is simply to set the color to a &#8220;legal&#8221; (documented, non-transparent) color before setting the transparency values:</p>
<pre lang='matlab' highlight='2'>
hArea = area(ydata);
hArea.FaceColor = 'b';  % or any other non-transparent color
drawnow; pause(0.05);  % this is important!
hArea.Face.ColorType = 'truecoloralpha';
hArea.Face.ColorData(4) = 40;  % 40/255 = 0.16 opacity = 84% transparent
</pre>
<p>Now the transparency settings are preserved, even when the figure is printed, saved, exported, resized etc.<br />
The obvious explanation is that by manually updating the graphic object&#8217;s <b>FaceColor</b>, Matlab automatically updates the hidden property <b>FaceColorMode</b> from &#8216;auto&#8217; to &#8216;manual&#8217;. This signals the graphics engine not to override the <b>Face</b>&#8216;s color when such an update would otherwise be called for. The mechanism of having a <b>&lt;PropName&gt;Mode</b> property associated with the <b>&lt;PropName&gt;</b> was used in HG1 (Matlab&#8217;s previous Matlab graphics engine, up to R2014a). In HG2, more properties have added such associated <b>*Mode</b> properties. In most cases, these additional <b>*Mode</b> properties are hidden, as <b>FaceColorMode</b> is. I find this justified, because in most cases users shouldn&#8217;t update these properties, and should let Matlab handle the logic.<br />
Unfortunately, this explanation is apparently false, as evident by the fact that setting <b>FaceColorMode</b> from &#8216;auto&#8217; to &#8216;manual&#8217; does not have the same desired effect. So for now I don&#8217;t know how to explain this phenomenon. At least we know it works, even if we don&#8217;t fully understand why [yet]. Oh well, I guess we can&#8217;t win &#8217;em all&#8230;<br />
Have you discovered and used some other interesting undocumented feature of HG2? If so, please share it in a comment below, or email me the details.</p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/persisting-transparent-colors-in-hg2">Persisting transparent colors in HG2</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/transparent-legend" rel="bookmark" title="Transparent legend">Transparent legend </a> <small>Matlab chart legends are opaque be default but can be made semi- or fully transparent. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-uipanels" rel="bookmark" title="Transparent uipanels">Transparent uipanels </a> <small>Matlab uipanels can be made transparent, for very useful effects. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-matlab-figure-window" rel="bookmark" title="Transparent Matlab figure window">Transparent Matlab figure window </a> <small>Matlab figure windows can be made fully or partially transparent/translucent or blurred - this article explains how...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/transparent-labels" rel="bookmark" title="Transparent labels">Transparent labels </a> <small>Matlab labels can be set to a transparent background as well as padding. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/persisting-transparent-colors-in-hg2/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
