HG2 update

Exactly three years ago, I posted information (here and here) about Matlab’s upcoming new graphics engine, so-called HG2 (Handle Graphics version 2). At the time, I was sure that HG2 was just around the corner. But three years and six releases have passed, Matlab 7 turned into Matlab 8, and HG1 is still in use. I decided that it was time to revisit the latest state of HG2, as reflected in the latest release, R2013a (Matlab 8.1).

In the past few years, development of HG2 has apparently progressed to a stage where most of the kinks were ironed out. The latest HG2 appears to be quite stable, and in my experience most GUI/graphics utilities run as-is, without any need for tweaking. This is good news, which leads me to think that HG2 will be released soon. It is possible that this could happen as early as the upcoming release (R2013b, 8.2) but I have a gut feeling that it will be in R2014a. I also have a gut feeling that MathWorks will name that release 9.0 rather than 8.3, in keeping with its arch-rival Mathematica.

HG2 has improved grid lines, plot anti-aliasing and customizable everything (more on this below). Here’s a simple plot line as it appears in both HG1 and HG2:

hFig = figure('pos',[100,100,300,250]);
x = -10:0.1:10;
y = 1e7*sin(x)./x; 
hLine = plot(x,y);
box off; grid on;
title('HG2 plot');

HG1 plotHG2 plot

Same plot in HG1 and HG2

We can see that MathWorks has invested heavily in improving usability. The graphics are now much more visually appealing than before. A lot of thought has gone into small details such as the plot colors and the axes gray shades. The changes are small when taken separately, but the overall gestalt is striking. HG2 will definitely justify my license maintenance cost.

Addendum Oct 3 2014: HG2 is finally released in Matlab release R2014b (8.4 – not 9.0 as I surmised above). However, many of the advanced customizations shown in this article are still unsupported and undocumented. I plan to detail them in a separate upcoming series of articles.

Highly customizable

Matlab in HG2 mode acts and behaves pretty much as you would expect. There are no visible changes to the Desktop or the graphics interface. The major difference is that all graphics handles, whether interactive controls (figure, uicontrols, uitables, etc.) or graph elements (axes, lines, patches, etc.) are instances of class objects (e.g., matlab.ui.Figure or matlab.graphics.chart.primitive.Line) rather than numeric values. This makes it easy to issue commands such as:

hFig.Color = 'w';
hAxes = gca;
hAxes.Title.Color = 'm';  % default: [0,0,0] = black
hAxes.YRuler.SecondaryLabel.String = 'millions';  % original: 'x10^{6}'
hAxes.YRuler.SecondaryLabel.FontAngle = 'italic';  % default: 'normal'
hAxes.YRuler.Axle.LineStyle = 'dotted';  % default: 'solid'
hAxes.YRuler.Axle.ColorData = uint8([0,100,0,255])';  %=dark green; default: [51 51 51 255], corresponding to [0.2 0.2 0.2 1]
hAxes.YBaseline.Color = 'b';  % default: [0.2 0.2 0.2]
hAxes.YBaseline.Visible = 'on';  % default: 'off'
hAxes.XRuler.Axle.Visible = 'off';  % default: 'on'
hLine.Color = [1,0,0];  %='red'

rather than using the corresponding set(…) or get(…) functions, which are still supported for backward compatibility.

Customized HG2 plot

Customized HG2 plot

Notice how much more customizable HG2 is compared to HG1. I am pretty excited from the huge number of additional possible customizations in HG2 compared to HG1. It is real a pity that many of these customizations rely on hidden/undocumented properties (see below). Hopefully this will change when HG2 is officially released.

Some observations

Here are a few observations that I collected on the latest HG2, as reflected in R2013a:

  1. Java is still supported (hurray!). The warnings about the figure’s JavaFrame property becoming deprecated have fortunately not been fulfilled (hopefully never). All the Java-based GUI tricks shown on this blog and in my book still work, excluding some minor things here and there which are due to inter-release changes rather than to the new HG2 engine.
  2. In order to access the top-level Java Frame of a figure window, we now need to use javaFrame.fHG2Client rather than javaFrame.fHG1Client. The relevant code should now look something like this, in order to be fully-compatible with older Matlab releases:
    jFrame = get(handle(hFig), 'JavaFrame');
        % This works up to R2011a
            % This works from R2008b and up, up to HG2
            % This works in HG2
  3. Anti-aliasing of plot elements (a.k.a. line -smoothing) is now ‘on’ by default (double hurray!). Apparently, MathWorks solved the problems with the existing undocumented LineSmoothing property. Still, for some unknown reason, LineSmoothing remains a hidden/undocumented property. Note that for some objects the property name is different. For example, the axes title (which is a text object of class matlab.graphics.primitive.Text) has a new property called Smoothing that controls anti-aliasing (unlike LineSmoothing, Smoothing appears to be an un-hidden fully-documented property).
    R2013b addendum: The figure handle now includes a property called GraphicsSmoothing that controls anti-aliasing at the entire figure level (default=’on’). No more need to set individual graphic elements, although we still can if we want (alas, this flexibility may be removed soon – see item #6 below). I would have liked to see the anti-aliasing feature use the same property name for all graphic elements, rather than GraphicsSmoothing/LineSmoothing/Smoothing, but maybe I’m just being an ungrateful spoil-sport… The good news about GraphicsSmoothing is that this is a non-hidden property. This means it can be seen with get(gcf) and once HG2 becomes live it will become fully documented/supported – hurray!
  4. Many new properties have been added to graphic objects, that enable customization of different aspects. For example, we can customize the axes grid-lines, containing box and exponent labels in ways that were impossible in HG1 (triple hurray!). Note that many of these new properties are hidden/undocumented (why the hell for???), so we need a utility such as my uiinspect or getundoc to detect them. Some of the useful new axes properties include *Ruler, *Baseline, *GridHandle, BoxFrame and BackDrop (I showed an example usage of *Ruler and *Baseline above). I have absolutely no idea why these so-useful properties are kept hidden, it simply makes no sense.
  5. Some existing HG1 properties are missing. For example, the UserData property is no longer available for some Java objects (this is a real pity — I depended on it for many functionalities, such as storing node-specific data in uitree/JTree nodes). Similarly, axes no longer have *LimInclude properties (this actually makes sense – these properties are still available in plot lines, where they actually have a use).
  6. Some existing HG1 properties now issue a warning, although they still work. For example:
    >> hAxes.DrawMode = 'fast';
    Warning: The DrawMode property will be removed in a future release.
    (Type "warning off MATLAB:hg:willberemoved" to suppress this warning.) 
    >> hLine.LineSmoothing
    Warning: The LineSmoothing property will be removed in a future release.
    (Type "warning off MATLAB:hg:willberemoved" to suppress this warning.) 
    ans =

    R2013b addendum: hAxes.DrawMode no longer issues a warning, although hLine.LineSmoothing does.

  7. There is an open bug on R2012b and R2013a whereby the clf function does not delete javacomponent objects. This bug does not affect HG2, where clf works properly.
  8. Some GUI components are being placed a pixel or two sideways in HG2 compared to HG1. This has no visual importance except in very rare cases, but it does affect my findjobj utility, which relies on the component’s position to find its underlying Java object. I have updated findjobj for the upcoming HG2 and it should work with both HG1 and HG2.
  9. The default axes and labels color has changed from black to gray ([0.2 0.2 0.2]). Grid lines now use an even lighter gray shade. Visually I think that this is a great change, since it directs the viewer’s focus on the plot contents rather than the external decorations.
  10. The default axes plot color order has changed. The standard plot color is no longer blue (as it was for ages in Matlab), but a bluish tint; the second color is no longer red but light green; the third color is reddish rather than dark green, etc.:
    % HG1
    >> get(0,'defaultAxesColorOrder')
    ans =
                0            0            1
                0          0.5            0
                1            0            0
                0         0.75         0.75
             0.75            0         0.75
             0.75         0.75            0
             0.25         0.25         0.25
    >> get(0,'defaultAxesColorOrder')
    ans =
         0.070588      0.40784      0.70196
          0.92941      0.14118      0.14902
          0.60784       0.7451      0.23922
          0.48235      0.17647       0.4549
                1      0.78039            0
          0.30196       0.7451      0.93333
          0.82353       0.4549            0

    R2013b addendum: The default colors have changed a bit (for the better I think). I still think that the relative order should more closely match the current order (blue-green-red-etc.), for compatibility with existing apps. A small utility function could be added that modifies the color-order to something that may be better suited for color-differentiation (see Tim Holy’s excellent utility for an example).

  11. HG2 axes no longer forget the previous plot color (unless we used hold all) — in HG2 color cycling is on by default. Note that this causes some visual discrepancies between HG1 and HG2 in plots that use hold on and have multiple plot lines: In HG1 they were all blue; in HG2 the first is bluish, the second is greenish, then reddish etc.
  12. GUIDE is still the same-ol’ GUIDE (sigh!). The figure toolbar and menubar have likewise not been upgraded, as far as I could tell.
  13. HG2 performance appears to be generally slower than HG1. Hopefully this will improve by the time HG2 is released, since performance has been one of HG1’s drawbacks all along. In my tests, most GUI/graphic aspects ran only slightly slower in HG2, except for 2D plots that were significantly slower. This is corroborated by running bench: on my computer, HG1 yields 0.4 for 2D and 0.22 for 3D; in HG2 the performance is 2.1 for 2D and 0.18 for 3D. Looks like the 2D performance still needs some work…

Testing HG2

As noted in my original article, we can start Matlab in HG2 mode by simply adding the startup (command-line) switch -hgVersion 2 to the Matlab command (note the space between the -hgVersion and the “2”). For example, in Windows, all you need to do is to copy your Matlab shortcut sideways (so that you will always have the standard HG1 version available), then right-click the shortcut, select “Properties”, then add -hgVersion 2 to the Target field (note the space between “hgVersion” and “2”). You will probably want to also add the “HG2” descriptor to the shortcut name, in the “General” tab:

Matlab startup switch for HG2

Matlab startup switch for HG2

If you have any Matlab application that relies on GUI or graphics, I urge you to test it on the new HG2 system. It’s trivially simple and your application should work exactly the same, or better. If you do detect some incompatibility, please post a comment or shoot me an email. In due course I expect that MathWorks will open an official channel for this, but in the meantime I’ll be sure to pass the information to the relevant person.

Do take a moment for testing HG2 – we can all contribute to ensure that when HG2 does come out it will be perfect. It’s in our interest.

NYC visit

If you happen to be in New York next week, I urge you to attend the MATLAB Computational Conference on Thursday May 23 (free registration; my presentation is scheduled for 4:50pm). I would be happy to meet you to discuss how I could bring value to your needs, either financial-oriented or not. We could meet at the conference, or anywhere in New York on Wednesday May 22 or Friday May 24.

Matlab Computational Finance Conference - 23 May 2013

Categories: Figure window, GUI, Handle graphics, Hidden property, Low risk of breaking in future versions, Stock Matlab function, Undocumented feature

Tags: , , , , , , ,

Bookmark and SharePrint Print

134 Responses to HG2 update

  1. Malcolm Lidierth says:


    Does this require Java 7? On a Mac with Java 6 and R2013a I get:

    Library not loaded: /System/Library/Frameworks/JavaVM.framework/Libraries/libjawt.dylib


    • Yair Altman says:

      @Malcolm – it shouldn’t, but then again I only tested it on Windows. The -hgVersion 2 switch has been around for several years, way before J7 was around. Perhaps it will work on an earlier release.

    • Malcolm Lidierth says:

      A quick check shows the dylib is present in the Apple 6 JRE. I’ll explore this on Windows. The Mac MATLAB can lag behind.

    • Malcolm Lidierth says:

      With a further look I have got HG2 running on a Mac Pro with NVidia 9400M graphics.
      For XP on BOOTCAMP, update to the graphics driver did the job.
      For OS 10.8.3, loading the latest CUDA 5 driver seemed to fix the problems – though why that would make a difference I have no idea.

  2. Stephan says:

    I’m trying to create a image in a vector format. HG1 cannot do this, as soon as there are color gradients or transparency. HG2 seem better in this case but seems to have trouble with the bounding box when saving to emf. pdf gives error messages and neither ghostview nor irfanview can open the resulting eps.

    surf([1 1;2 4], 'FaceColor', 'interp', 'FaceAlpha', 0.5)
    set(gcf, 'renderer', 'painter')
    saveas(gcf, 'C:\temp\aaa.emf')
    saveas(gcf, 'C:\temp\aaa.pdf')
    saveas(gcf, 'C:\temp\aaa.eps')
  3. Jayveer says:

    Hi Yair

    Do you reckon this can be used for MATLAB compiled applications? Will it be stable enough?



    • @Jayveer – I don’t know, it’s a good question. I think it’s stable enough, the only question is whether the compiler will use the HG1 or HG2 library when compiling the application. The only way to find out is to try it out. Let us know what you find!

    • Stefan says:

      Per default, MATLAB Compiler (or rather, the Runtime) will use hgVersion 1 although MATLAB itself uses hgVersion 2.

      To change this, you need to pass the option to the Runtime, by opening the “Settings” Window in the compiler and adding

      -R '-hgVersion,2'

      in “Additional parameters to be passed to MCC”

      This will make it work for me, although with some additional weird behaviours like in my case the window will be a little bit too small… Haven’t found any show-stoppers yet though. Up to you to decide whether you would want this for production use – I usually check whether it works for a particular tool, and just go for hgVersion 1 otherwise…

      I am using 2013b, and seems to be the same in 2014a

  4. I noticed that it is still possible to get old numeric handle, if it is needed: hNumeric = double( hObject );

    GET/SET both work for those numeric handles.

    Yet, the overall HG2 performance is unacceptably low for our GUI-intensive application. I can literally see each button and textfield drawn separately. There is also an issue with positioning text labels in Pixel units.

    In addition, graphics driver (ATI Radeon 3650) crashed the first time I’ve started the application.

    • Yair Altman says:

      @Alexander – you can use get/set with both the numeric handles and the class-object values. With HG2, I see no reason to use numeric handle values anymore.

    • Alexander Kosenkov says:

      I was passing the handle to my Java code in order to work on it later. After switching to HG2, of course, I got an error about mismatched types. Simply casting the handle to double fixed everything.

      Maybe this is the only case when such cast is needed.

    • Malcolm Lidierth says:

      On Windows, activating DirectX via a java.opts file might (?) improve GUI component performance.
      The general speed is low but, hopefully, that will because there is debug code in there for TMW.

    • Yoav says:

      Thanks Alexander! The double(hFig) is exactly what I was looking for.
      I’m heavily using the WindowAPI function from the matlab file exachange (http://www.mathworks.com/matlabcentral/fileexchange/31437-windowapi).
      Unfortunately, it only accepts numeric handles.
      So, WindowAPI (hFig,’Maximize’) doesn’t work with HG2.
      However, WindowAPI (double(hFig),’Maximize’) works just fine… Thanks!

    • Alexander Mering says:


      I do see problems related to heavy GUI’s. In my GUI, I use 8 Java buttons, 2 CheckboxTrees and overall 8 JScrollpanes with JideTables. (Yeah, all on the same GUI).

      Since I replace the row- and columns headers (as well as the corners) of the tables by further java elements, I experience the following behavior:

      Using HG2, the buildup-time of the GUI becomes that long, that the code is already trying to access properties which do not exist yet. Using HG1, GUI buildup (or most likely the display and generation) time is fast enough to make the elements exist right before the code tries to access the elements.
      With HG2, the prolonged buildup-time leads to “Attempt to reference field of non-structure array.” errors.

      Ok, when trying to build an reduced example (see below) I must admit that this is also the case for HG1. Some parts of the Scrollpane manipulations need to wait until the element is displayed. In the reduced example, a simple drawnow makes it for HG1 and HG2. In my GUI, even a longer pause is not enough. So I still see severe timing problems with HG2 – the GUI could not be build up.

      Reduced example:
      JScrollpane with a table and additionally the RowHeaders are replaced by a 3 column table (Having two tables side-by-side):

      Parent = figure('Position', [10 10 1000 800], 'Color', [0 0 0])
      num_rows = 40;
      Tag = 'Table';
      bg_color = java.awt.Color(0, 0, 0);
      jtable = javaObjectEDT('com.jidesoft.grid.JideTable',num_rows, 4);
      scrollpane = javaObjectEDT('javax.swing.JScrollPane', jtable);
      [jhandle,mhandle] = javacomponent(scrollpane, [ 50 50 900 700], Parent);
      jhandle = javaObjectEDT(jhandle);
      %% completely redo the headers.
      needed_header_dimension = [num_rows, 3];
      %% Row header
      header_table = javaObjectEDT('javax.swing.JTable', needed_header_dimension(1),needed_header_dimension(2));
      %% upper left corner = Row headers header (empty place)
      upper_left_corner = javaObjectEDT('javax.swing.JLabel');
      %% Further Layout manipulations
      % manipulate further colors
      jhandle.setBackground(bg_color) % alternatively: jhandle.setBorder(javax.swing.BorderFactory.createEmptyBorder())
      fprintf(1, '\nNow it fails without drawnow:\n')
      % drawnow
      jhandle.getColumnHeader.getView.setBackground(java.awt.Color(1, 0, 0))
  5. Greg says:

    Wow, thanks, this is amazing!

    A few comments:

    – I’ve been testing out HG2 features on Linux (Red Hat Enterprise 6.4) and everything seems to be working well.

    – The difference in plot quality on large 3-D meshes created with “patch” objects is simply astounding. While creating these plots seems to be slower with HG2, rotating the plots actually seems faster, even with transparency turned on.

    – There used to be a “bug” (though I’m not sure it’s officially considered a bug) in HG1’s “print” function where text would get smaller and smaller the higher the resolution you printed a figure at. This used to mean that when I printed figures to .png files at high enough resolutions to make curves look smooth, the labels and legends were illegible. This seems to be resolved in HG2 and it is now possible to print at very high resolutions and still get readable legends.

  6. Pingback: HG2 for Better Graphics in MATLAB « Labrigger

  7. Eric says:

    Very cool! Yair, is there a way to set some sort of property in HG2 to have lines use some sort of pchip/spline to interpolate smoothly between the data points, instead of being piecewise continuous? I poked around a little in the properties for Line objects, but didn’t see anything…


    • @Eric – I have’t seen something specific about this. The new DataSpace property may somehow be related, but I don’t know. I think your best bet is to interpolate programmatically before plotting – this way you will have the best control over how the interpolation will work.

    • Eric says:

      Yair, I think the DataSpace property might be for choosing between mappings such as cartesian, polar, etc. I’m not sure if this is implemented/exposed though?

      BTW, why does it seem that there is only a ‘reply’ button on certain comments?

    • @Eric – I’m not sure (yet…) what DataSpace does.

      As for the <Reply> button, it is available on the top comment of each thread. Clicking it will add your comment to the bottom of the thread.

    • Eric says:

      @Yair, would it be possible to enable ‘Reply’ links on each comment, which would place it nested under the comment that you replied to? It would make it easier to follow comment threads, and minimize the need for the adhoc @username system :)

    • @Eric – as you can see from your reply, this is done automatically. All this is a result of my design decision to limit comment threads to a depth of 2.

  8. Volkmar says:

    Works in HG1 only:

    function close_hg1
    f = figure;
        'Position',[.1 .1 .8 .2],...

    In HG1, delete() is not picky about the additional arguments passed on to a GUI callback. In HG2 this raises an error.

    To make it work in HG1 and HG2, one has to use a wrapper function to delete the button object:

    function close_hg2
    f = figure;
        'Position',[.1 .1 .8 .2],...

    This wrapper function accepts all event data and calls delete with exactly one object handle:

    function mydelete(varargin)
  9. Bukmop says:

    R2013a is 8.1 … not 8.2!
    R2013b will probably be 8.2 … please fix to not confuse people

    • thanks for the correction, it’s now fixed
      I have no intention of confusing people, but I am only human – even I make mistakes sometimes.
      There’s no need for angry words.

    • Bukmop says:

      Just mentioned typo. There were no angry words

  10. Kesh says:


    I like what HG2 produces on screen; however, I cannot seem to print any HG2 figures. Do you know of any work around? (Win64)

    For example:

     print -dpng test.png

    errors out with error message:

    Error using writeRaster (line 26)
    Invalid CData, must be MxNx3; not calling IMWRITE.
    Error in C:\Program
    Files\MATLAB\R2013a\toolbox\matlab\graphics\private\alternatePrintPath.p>LocalGenerateFileOutput (line 588)
    Error in C:\Program Files\MATLAB\R2013a\toolbox\matlab\graphics\private\alternatePrintPath.p>alternatePrintPath
    (line 72)
    Error in print (line 232)
        pj = alternatePrintPath(pj);

    P.S., Sorry about not following through with you on java sound article. I revisited my code and couldn’t even recall what I exactly did…

    • Yair Altman says:

      @Kesh – it works on my Win7 x64. I’m not sure what the specific issue is with your installation.
      Perhaps try these two lines on a fresh ML session?
      I’d normally have pointed you to MathWorks support, but since HG2 is still unofficial that would not be of use.

  11. matt dash says:

    Do you know how HG2 handles the java canvases? In HG1 I use findjobj(fig,’class’,’AxisCanvas’) to get the canvas, which I then use to get a Graphics object (AxisCanvas.getGraphics) that I use to create FontMetrics. It looks like in HG2 the canvas class is either JavaSceneServerCanvas or JavaSceneServerGLCanvas. I have been unable to get their handles using findjobj however (findjobj(fff,’class’,’JavaSceneServerCanvas’)). Maybe there an easier way to get a Graphics object that doesnt require the canvas handle at all…

    Also potentially interesting, a new figure with no axes has no canvas listed in findjobj.

    • Yair Altman says:

      @Matt – I do not know exactly how the Java canvas is used in HG2. As you have mentioned, the canvas object is somewhat different in HG2 compared to HG1. The HG2 canvas is a direct extension of javax.media.opengl.GLCanvas. You can access the canvas object as follows:

      jCanvas = hFig.JavaFrame.fHG2Client.getAxisComponent.getComponent(1).getComponent(0);

      This canvas is only added to the figure when an axes is drawn (presumably, for performance and resources reasons).

  12. Frank says:


    Thanks for the helpful article on HG2. When attempting to copy a figure, I got the following errors:

    Error using uimenufcn
    Invalid object handle
    Error in editmenufcn (line 78)
                uimenufcn(hfig, 'EditCopyFigure')
    Error while evaluating Menu Callback

    The figure was initially created with function imagesc, and plots were added to the figure with function plot. Some text was also added to the figure with function text. Clipboard format in figure copy options was set to “Preserve information (metafile if possible)” and figure background color “Transparent background.”

  13. Emmanuel says:


    Thanks for this news on HG2, I am now using it to render my GUI apps. :)

    One question though, how do I do a check if whether MATLAB is on HG1- or HG2-mode? This would help in debugging HG-compatibility related issues and would also make functions flexible on both environments.

    • Yair Altman says:

      @Emmanuel – you can use feature(‘UseHG2’) or feature(‘HGUsingMATLABClasses’) – both return a true/false value based on whether or not you’re using HG2. See more feature options here.

  14. Julie Liu says:

    it seems like naked java references via set(…) is not supported in the HG2 engine

  15. Pingback: A couple of internal Matlab bugs and workarounds | Undocumented Matlab

  16. Domenico says:

    Hello Yair,

    the following two lines lead to an error when running under “HG2” option, they ran without problems with default engine.

    h= uitree('v0')
    set(h,'Position',[100 200 300 400]

    I got the error message:

    Error using javahandle_withcallbacks.com.mathworks.hg.peer.UITreePeer/set
    Java exception occurred:
    java.lang.Error: com.mathworks.jmi.MatlabException: There is no Position property on the Root class.
    at com.mathworks.hg.peer.FigureChild.updateHGProxyPosition(FigureChild.java:289)
    at com.mathworks.hg.peer.FigureChild.updatePosition(FigureChild.java:258)
    at com.mathworks.hg.peer.FigureChild.setPosition(FigureChild.java:317)
    Caused by: com.mathworks.jmi.MatlabException: There is no Position property on the Root class.
    at com.mathworks.jmi.NativeMatlab.SendMatlabMessage(Native Method)
    at com.mathworks.jmi.NativeMatlab.sendMatlabMessage(NativeMatlab.java:265)
    at com.mathworks.jmi.MatlabLooper.sendMatlabMessage(MatlabLooper.java:120)
    at com.mathworks.jmi.Matlab.mtFeval(Matlab.java:1541)
    at com.mathworks.hg.peer.FigureChild.updateHGProxyPosition(FigureChild.java:284)
    ... 2 more

    This error is posted to the Matlab team and I will inform you about their answer.

    Best regards and thanks for this excellent page,

    • Domenico says:

      Problem above sent to the “standard” technical support. “Standard” answer: As already known whether HG2 option nor uitree are supported, but information has been forwarded to the developers. Cheers, Domenico

  17. Dirk Poot says:

    HG2 looks nice indeed. Thanks for telling about it!

    I do encounter a problem though. I don’t succeed in setting a colormap for an axes placed inside a uipanel while in HG1 it just used the figure colormap:

    panel = uipanel('Position',[.5 0 .5 1]);
    subfigs = axes('OuterPosition',[0 0 .5 .5],'parent',panel);
    img = uint8(256*rand(100,100));
    imghndl = image(img);
  18. Benj FitzPatrick says:

    This looks terrific, though I am having some difficulties using almost all of the modifications you specify above. I have tried 2012b and 2013a on linux and 2013a on windows 7, and all of them behave identically. I copied the commands you use to make the plot in the first code box, and then I try one of the alterations in the 2nd code box. The only two that work are hFig.Color = ‘w’; and hLine.Color = [1,0,0]; However, hAxes are not recognized as valid graphics objects using ishandle(). Have I missed a gca or gcf command that will pick up the current axes so I can modify the axes, labels, and title?

    • @Benj – naturally: hAxes is the handle returned by either the axes or gca functions, just as you would expect in the current system (HG1).

    • Benj FitzPatrick says:

      *face palm* Thanks Yair. Running hAxes=gca; fixed everything. Sorry for the dumb question and thanks for all of the above info.

  19. Werner Freund says:

    I’ve found a minor bug with uicontrol, HG2 and findjobj:

    >> figure
    >> k=uipanel('Visible','off');
    >> m=uicontrol('Parent',k);
    >> jM=findjobj(m)  % handle: 1-by-0
    >> k.Visible = 'on';
    >> jM=findjobj(m); % javahandle_withcallbacks.com.mathworks.hg.peer.PushButtonPeer$1

    The workaround:

    >> figure
    >> k=uipanel;                 
    >> k.Visible = 'off';
    >> m=uicontrol('Parent',k);
    >> jM=findjobj(m);  % javahandle_withcallbacks.com.mathworks.hg.peer.PushButtonPeer$1

    My guess is that the panel needs to be rendered to create the java object… but I trust in your guess much more than in mine…

    • Yes, this is correct – the panel needs to be rendered at least once for the Java peer to be created. Creating the panel in invisible mode apparently does not do this. For a similar reason findjobj often fails in the *_OpeningFcn() function of a GUIDE-generated m-file, and needs to be done in the corresponding *_OutputFcn().

    • Werner Freund says:

      Anyway, findjobj seems to work perfectly at HG2 x)

  20. prashant singh says:

    In matlab7.0 there is no component for frame in GUI.
    SO,how can i add frame componenet in Matlab for gui?
    Plz reply

  21. Pingback: Rich-contents log panel | Undocumented Matlab

  22. Benj FitzPatrick says:

    Yair, have you noticed that if you use hLine.LineWidth=3.0; (anything larger than 1.0) that the line develops bites taken out of it (generally on either side of a local max or min)? This doesn’t appear to be a line smoothing issue, but it certainly pertains to HG2 because this problem disappears when I go back to HG1. Any thoughts?

    • Luke Hollmann says:

      Similarly, any combination of (‘LineWidth‘ > 1.0) and (‘LineStyle‘ ~= ‘solid’) seems to make the line disappear entirely, regardless of the ‘Color‘ of the line.

  23. Julien says:

    Hello, I tested the HG2-version with one of my GUIDE figure. Unfortunately, it has erased the old figure with new handles properties. Now I would like to go back to HG1 version, but I can no longer use my GUIDE figures due to this error :

    File test1.fig contains objects that have been saved in a future version (8.0.0 or later) of MATLAB. To load the file in this version it must be saved using a compatibility flag in hgsave.

    I tried to use hgsave in HG2 mode with ‘-v6’ option, but it doesn’t seems working. Do you have an idea to fix it?

    Thank you in advance

    • Yair Altman says:

      @Julien – open hgsave.m in the editor (edit hgsave) and modify the main condition in line #47 as highlighted below:

      46:  % Decide which save code path to use
      47:  if true  %graphics.internal.graphicsversionWithEmpty(h, 'handlegraphics') 48:      FF.Format2Data = hgsaveStructDbl(h, SaveAll);
      49:      FF.RequiredMatlabVersion = 70000;
      50:  else
      51:      FF.FigFormat = 2;
      52:      FF.Format3Data = hgsaveObject(h);
      53:      FF.Format2Data = hgsaveStructClass(h) ;        
      54:      FF.SaveObjects = true;
      55:      FF.RequiredMatlabVersion = 70000; 
      56:  end
      58:  FF.write();

      You can now save figures regularly in HG2 – it will only use the HG1 code-path, i.e. save the handles in double format.

    • Julien says:

      Hello Yair,

      Thank you for the quick answer. I can’t edit hgsave on my current matlab version (2013a) due to not administrator rights. I tried on a laptop withs these rights to allow me editing files saved on C hardrive but the matlab version is 2012b. The hgsave file seems a little bit different, but I modified this :

      % Decide which save code path to use
      if true %isempty(h) || graphicsversion(h, 'handlegraphics')
          % Warn if user passed in 'all' flag
          if SaveAll
          hgS = hgsaveStructDbl(h, SaveAll);
          SaveVer = '070000';
          SaveOldFig = true;

      then I got the following error line

      No appropriate method, property, or field serializeDatatips for class matlab.graphics.shape.internal.DataCursorManager.

      Error in hgsaveStructDbl (line 58)

      Error in hgsave (line 62)
      hgS = hgsaveStructDbl(h, SaveAll);

    • Yair Altman says:

      In your R2013a, place a breakpoint in line 47, then save and when it stops at line 47 try to run the following directly in your Matlab Command Window:

      >> FF.Format2Data = hgsaveStructDbl(h, SaveAll);
      >> FF.RequiredMatlabVersion = 70000;
      >> FF.write();

      If this works, then simply stop debugging at that point. If you still get internal errors as in R2012b, then you’ll need to place internal breakpoints there to control the processing flow. No easy fix that I know of.
      Anyway, for this you don’t need admin rights.

    • @Julien – Please retest when the R2014a pre-release comes out in December, and let us know if it works for you. I believe that it may be fixed by then.

  24. nic says:


    After trying hg2 in Matlab2013b, I found that anyone interested in using the hg2 under a 64bit Linux system with an NVidia card may experience some problems right now. It seems that the javax.media implementation that is used for hg2 (and installed on my system) depends on EGL capabilities, which NVidia’s current 331.13 driver does not expose under a 64bit system.

    I noticed this today, as I was putting an NVidia GTX550 into my PC and the hg2 plots didn’t show anymore. The only warning message that I got was when trying to plot(0:0.1:5, sin(0:0.1:5)): “libEGL: DRI2: failed to authenticate”. As I’m not too familiar with javax, I can’t tell you if my assumption is fully true or related to something else. However using the onboard Intel GPU with the corresponding Intel driver and Mesa OpenGL shows the plots.


  25. Pingback: Draggable plot data-tips | Undocumented Matlab

  26. Michael says:

    One thing that has bothered me in Matlab for a long time, is the absence of an alpha property for lines. It’s possible to make transparent patches, but as soon as it comes to lines, there seems to be no way. Do you know whether this has been fixed in HG2?
    I already tried it, and searched the properties, but couldn’t find any. What I also noticed are these huge title font sizes, that start to obscure the x-axis label in a multiplot and that the whole thing doesn’t seem to be very stable. When I try to edit properties in the figure editor, it is really slow and prone to crashing. I don’t think this thing will be released anytime soon. Maybe in 2 years or so, but it doesn’t even seem to be the case that Mathworks is really putting effort it. The HG2 apparently has been around for quite some time now.

    • @Michael – colors in HG2 can be either 3 numeric values (as in HG1, representing the RGB channels), or 4 values – the 4th value is the alpha channel (0.0=transparent, 1.0=opaque). So, for example, the following will create an almost-transparent blueish line:

      h=line(1:5,4:8, 'LineWidth',4, 'Color',[0,0,1,.2]);
    • Michael says:

      Oh, awesome! Finally there.

      However, I’m having the problem that there is no way to save the graphs. It either looks like before with slightly changed colors, or it is rendered into a pixel output. print(h,'-depsc','myfile') for example gives me an eps with embedded bitmap image that looks horrible. Same for trying to save it via the file dialog, everything looks saved much more ugly as on screen, with the anti-aliasing gone and no vectors left. Only when I copy the figure, I get a vectorized result pasted into illustrator, but the x-axis is shifted.

    • HG2 obviously still has bugs, which is the reason it has still not been released. The more such bugs that people report here, the more MathWorks will be able to fix them before the official release. Until then, this is the unofficial place to report HG2 issues. Behind the scenes I am ensuring that the relevant MathWorkers are made aware of them. So please keep reporting any kinks that you find.

    • Michael says:

      Ah, that’s great. Thanks a lot. I would really like the better graphics to be released. I have bugged Mathworks several times concerning this problem. Is there any solid estimate when it might come out?

      I found a way to still save in vector format, this is, when I set the renderer to painters. However, the saved file will have lost the alpha shading and be black again.

    • Michael says:

      Ok, I think I know now what’s happening. The default renderer is set to OpenGL i I plot some lines with transparency. If I set the renderer to painters, I still get the correct transparency displayed. However, if I now save it, the transparency info is lost. Painters didn’t support transparency in previous releases, which didn’t really have any impact, since there was none for line plots, and for 3D plots Matlab never outputted vectors graphics anyway. So the problem now is, that they have a nice little graphics engine but no way to pass the new features onto any saveable output. Sad.

      My general impression of the HG2 in 2013b is, that it matured quite a bit since 2013a, but for some reason the 3rd plotted color is now orange. Why? Just why? Previously it was green and that made sense because it was RGB backwards and could be well used to plot info from image file channels. Now I have to manually change the color. A lot of plots made in the past are going to look very different and maybe be even useless (e.g. if the background color is non-white). Why would one do that? It has absolutely no benefit that I could see other then being “new”.

    • Yair Altman says:

      @Michael – I can’t answer about the vector export issue. I tend to agree with you on the face of it, but I haven’t really looked into it and there might well be a solution in HG2. Let me rephrase – I’d be surprised if there isn’t a solution to it somewhere, we just need to discover it…

      Regarding the color order, I think MathWorks made a very extensive usability study before changing the colors, with respect to different varieties of CVDs (color-vision deficiencies, AKA “color-blindness”) and visual perception. I think that the overall gestalt is much better than before. They have certainly not changed it just for the sake of being “new” as you imply, I’m pretty certain that some scientist has found that orange looks better than green when plotted alongside red and blue. Still, I agree with your point regarding preservation of green (or a greenish hue) as the third default color, for backward compatibility sake. It is exactly this sort of feedback, with actual use-cases, that can help MathWorks better align their decisions (in this case, opt for a slightly-less-than-optimal visual perception for the sake of preserving backward compatibility).

      So keep those use-cases flowing :-)

  27. Pingback: Performance: accessing handle properties | Undocumented Matlab

  28. Mafen says:

    In hg2 mode, the “copy figure” command in “Edit” menu doesn’t work…

  29. erick says:

    In Matlab R2011a in Ubuntu, I obtain the following error when creating a figure:

    >> plot(2,3)
           Segmentation violation detected ...
    Abnormal termination:
    Segmentation violation

    Any ideas?

  30. Julien says:

    Hi Yair,
    I guess you are playing with R2014a pre-release… Could you say if your prediction about HG2 release was correct??

  31. Hi Yair,

    HG2 on the mac seems to have problems with Java on my Mac OS X Maverick using 2013b :

    I get :
    >> X=1:100;
    >> figure(1)
    >> plot(X)
    Exception in thread “AWT-EventQueue-0” java.lang.NoSuchMethodError: javax.media.opengl.GLCapabilities.(Ljavax/media/opengl/GLProfile;)V
    at com.mathworks.hg.peer.JavaSceneServerPeer.getCaps(JavaSceneServerPeer.java:125)
    at com.mathworks.hg.peer.JavaSceneServerPeer.doCreateCanvas(JavaSceneServerPeer.java:942)
    at com.mathworks.hg.peer.JavaSceneServerPeer.access$200(JavaSceneServerPeer.java:44)
    at com.mathworks.hg.peer.JavaSceneServerPeer$2.run(JavaSceneServerPeer.java:914)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:682)
    at java.awt.EventQueue$3.run(EventQueue.java:680)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

    • And I agree dumping UserData is really annoying. It’s the only way to associate any object type with graphical objects.
      I use it a lot.

    • @Jerome – try rerunning on R2014a, maybe it’s fixed already. As for UserData, try replacing it with ApplicationData (which can be accessed directly as a property, or via the getappdata/setappdata/isappdata functions).

    • Hi Yair,
      Many thanks for the response. I will give a try. I am not sure I have access to 2014a yet.

      Do you have an idea which UserData has disappeared?
      I am using a lot of UserData in all list-related objects, like in uimenu, uicontrol, uitree, uitreenode.

    • @Jerome – I have not made a detailed study of the UserData aspect so I don’t know. Note that some Java objects have alternative native properties that you can use (e.g., UserObject for tree nodes).

  32. Thanks Yair,
    Your help is invaluable as usual.

  33. Pappu Murthy says:

    I have just tried HG2 Engine in version 2013b. When I looked at simple graph like y=x^2,it did look better on comp. screen with HG2 version, however, when printed the old graph unmistakeably looked superior to the new one. I did show these to my colleagues at NASA around here to confirm that. Not sure what is going on by I have sent the out put to you in a separate email as well.

  34. Pete Durningdale says:

    Im so disappointed, R2014a is here, but no official HG2, or a better working GUIDE :/

    • @Pete – have a little patience, it’s close. MathWorks is probably investing heavily in testing to ensure that it works as best as it could first time out-of-the-box. For one thing, they still can’t release HG2 with the horrid performance that I mentioned in the article, so I’m pretty sure that they are working hard to fix it. There were also some idiosyncrasies reported on various specific platforms/graphic cards that need to be resolved. It’s a major dev effort, so we need to be patient, even if it means waiting another release or two.

  35. Richard S-T says:

    The demo code did not work for me with R2013b on Win7-x64 with Nvidia Quadro 3000M graphics. The figure appears but only has a light blue-grey background. No errors are generated. The hFig and hLine variables created as expected.

    A pity. Ah well.

  36. Eike B. says:

    Just checked my gui out of curiosity using HG2 and it seems that your very nice uisplitpane function does not work:

    >> uisplitpane(figure(2), 'Orientation','hor', 'DividerLocation', 0.3);
    Error using matlab.ui.container.internal.JavaWrapper/horzcat
    While converting from 'javahandle_withcallbacks.com.sun.java.swing.plaf.windows.WindowsSplitPaneDivider':
     The conversion returned a value of class 'matlab.mixin.Heterogeneous', which cannot be inserted into an array of class 'matlab.ui.container.internal.JavaWrapper'.
    uisplitpane: No constructor 'handle.listener' with matching signature found.
    Error in uisplitpane>addPropListeners (line 1097)
        listeners(end+1) = handle.listener(hhDivider, findprop(hhDivider,'Extent'),
        'PropertyPostSet', @dividerResizedCallback);
    Error in uisplitpane>splitPane (line 488)
        listeners = addPropListeners(hFig, hDivider, h1, h2, listenedPropNames);
    Error in uisplitpane>splitPanes (line 373)
            [a,b,c] = splitPane(paramsStruct.parent(parentIdx), paramsStruct);
    Error in uisplitpane (line 136)
          [h1, h2, hDivider] = splitPanes(paramsStruct);
    No appropriate method, property, or field Orientation for class matlab.ui.container.internal.JavaWrapper.
    Error using matlab.ui.container.internal.JavaWrapper/get
    There is no orientation property on the JavaWrapper class.
    Error using matlab.ui.container.internal.JavaWrapper/get

    Do you have any knowledge on whether the new axes implementation works with JSplitPanes?

    • @Eike – the error is due to the way Matlab previously enabled, and now does not, concatenation of handles of different types. I hope to get around to fixing this sometime in the upcoming months. Unfortunately, this is not the only utility that I would need to update. When using undocumented aspects/features there is always the risk of forward compatibility, and so after each Matlab release I need to make changes to the existing code base to ensure that it still runs on both the older and the latest Matlab releases. Sometimes it’s easy, sometimes not.

    • Eike B. says:

      I totally understand! I am more than happy about the functions you provide for free, no complains from me.

      I made a quick and dirty try whether the new HG2 axes object could be directly used with JSplitPane but i guess it is not that easy and/or my knowledge about Java and Matlab is not advanced enough.

    • You cannot embed a Matlab component (axes in this case) in a Java container – only in other Matlab containers.
      The fact that you seem to be able to do it in a uitab is just a sophisticated optical illusion.

    • Eike B. says:

      I know. I read your book. It helps a lot for my current project. The thing I remembered wrong was that I thought it was only the axes container that could not be contained by a java container. So I hoped they perhaps changed that when developing HG2 but I guess it’s not the case.

    • The latest version of uisplitpane now supports HG2 (R2014b+), as well as remaining backward-compatible with earlier Matlab releases (hopefully…).

    • Michele says:


      Where Could I find the updated code of uisplitpane.m?


    • @Michele – uisplitpane is available on Matlab File Exchange: the https://www.mathworks.com/matlabcentral/fileexchange/23073-uisplitpane-split-a-container-into-two-resizable-sub-containers

      Also consider using the GUI Layout Toolbox that contains similar functionality

  37. Jonas says:

    On Red Hat 6.3, Matlab R2014 causes a segmentation fault when calling

    h=errordlg('this is a','test')

    . In the shell, it returns the warning “WARNING: Application /…/matlab/r2014a/bin/glnxa64/MATLAB\ufffd* calling GLX 1.3 function “glXCreatePbuffer” when GLX 1.3 is not supported! This is an application bug!”, then it tries spawning a java window, and closes. HG1 seems to work fine, though.

  38. hlk says:

    “We can see that MathWorks has invested heavily in improving usability. The graphics are now much more visually appealing than before.”

    Seriously? Don’t know if I’m the only one but “prettiness” is far down on my list concerning usability.
    Functionality, consistency and efficiency should be the prime concerns. With all the UI re-engineering in Java there’s plenty of room for fixing consistency let alone innovating.

    What good is it, for example, having pretty antialiased plots when you can’t pan and zoom them efficiently? There is not even much to innovate here, other software has been making excellent use of the mouse wheel for years!

  39. Sarah says:

    In testing my GUIs on HG2, I’ve found a few things. I’ll post them each separately.

    Win7 Enterprise, 64 bit; Matlab R2014a

    inputdlg: Using the stock example code from the help

    prompt={'Enter the matrix size for x^2:','Enter the colormap name:'};
    name='Input for Peaks function';

    gets the following error

    No appropriate method, property, or field PlotChildren_I for class opaque.
    Error in matlab.graphics.illustration.Legend/set.PlotChildren_I (line 2556)
    Error in textwrap (line 82)
    Error in inputdlg (line 201)
        [WrapQuest{ExtLp},QuestPos(ExtLp,1:4)]= ...
  40. Joe says:

    Thanks for this very helpful post. I’ve referred to it and its parents many times now. Since I’m not a beta tester and there is no obvious official place to mention HG2 bugs/oddities, I might as well post one I’ve observed here. I would be happy to be corrected if I’m wrong.

    On 10.9.2/R2014a/HG2, colorbar only displays the full colormap of the figure, no matter what Limits (formerly xlim or ylim) is set to. On the same system/version using HG1, appropriate adjustments to xlim and ylim result in a narrower colorbar, as in previous MATLAB versions. A workaround is to freezeColors and then trim the colormap as appropriate, but this approach is unsatisfactory if the figure is at all dynamic.

  41. William says:

    Seems like this does not work on on my computer. I actually have 2 different computers, both with 2013b. On one of them, Hg2 works fine but on the other i just get an empty figure where I dont see anything. No error messages are produced.

    When I copy and paste the (empty) figure into e.g. word or power point, I get a full graph so it seems like it there is something wrong with the plotting to the screen.

    Any ideas?

  42. alex says:

    The new graphics will be officially released in R2014b, just got my R2014b prerelease testing version.

  43. Pingback: Matlab’ın yeni çizim motoru: HG2

  44. jean says:

    Thank you for this post. I am using the HG2 and I wanted to know if you have experienced some issues with it. I am trying to save some figures made in HG1 in the new format and it is a very difficult process because Matlab slows down considerably. Also, in Guide I get an error that previously was not there in HG1. I am using R2013a.

    Best regards,

  45. Edouard Canot says:

    Hi all. I’m currently testing HG2

    My problem concerns EPS (Encapsulated PostScript figures) generation, which now are very bad.
    >> print -depsc2 myfig.eps
    now leads to a bitmap embedded inside an EPS file, and it looks weird.

    Opening the EPS file, it turns out that the figure is generated now by APACHE (Apache XML Graphics Commons: EPS Generator for Java2D) and not by the old PS generator of Matlab.
    As a side effect, the figure size is of course bigger than the old one (180 ko instead of 8 ko).

    The same behavior occurs when printing directly from the menu of the figure window.

    How can I generate true PostScript figures? I’m used to fix and modify things inside the EPS and this is very useful.

    Thanks for any advice.

  46. Denis says:

    Nice post. I’m using Matlab with the ‘new’ HG2. It behaves a bit different here and there but there is one thing I couldn’t solve by now. A high resolution background image is not saved in its original resolution any more. It seems as it always uses the screen resolution. With HG1 this example was working.

    img = imread(File);
    hold on
    plot(something ...)
    fig = gcf;
    fig.GraphicsSmoothing = 'off';
    fig.Renderer = 'painters';
    print -dpdf test.pdf

    Any Ideas?

  47. Pingback: Online (web-based) Matlab | Undocumented Matlab

  48. Philippe Roy says:

    Looks promising. However, I get a bug (R2012b, Linux 64bits) with the scatter function. With HG1, NaN values are not shown, while under HG2 they are shown like a “low” values. I mean, I have a vector which has values between 1961 and 2070. NaN values looks like 1961. I’m using scatter on a map projection with the m_map toolbox. Anyway, this bug is simply avoided by using HG1.

    • Yair Altman says:

      @Philippe – perhaps this is a bug in m_map, not HG2. You may wish to contact the m_map developer (Rich Pawlowicz). He seems to be maintaining m_map, the latest version came out in 10/2013.

    • Philippe Roy says:

      Thanks Yair, I found an easy workaround by plotting only non-nan values. The m_map toolbox is using the regular (i.e. built-in) “scatter” function from Matlab inside the m_scatter function (the m_scatter function just convert lat-long values to x,y figure values and then use scatter on those x,y values).

      I do have another question though. You say that the default color order in HG2 is different between R2012b (which I have and doesn’t like that much) and R2013b. Can you provide the color order from this R2013b release (or R2014a,b if it’s updated from R2013b) ? I’d like to use them but can’t find it anywhere.

    • @Philippe – you can get the color order on any Matlab release using:

      get(0,'FactoryAxesColorOrder')  % Default Matlab axes color order (factory values)
      get(0,'DefaultAxesColorOrder')  % Default Matlab axes color order (your updated settings)
      get(gca,'ColorOrder')  % color order for this specific axes
    • Philippe Roy says:

      Thanks Yair, but this command (i.e. factory and default color order) gives me the factory and default color order of R2012b, not the latest factory color order. As it is in R2012b, the color order is not really great (not bad, but not great). So I was merely wondering what was the color order of the latest release (since you are pointing out in the blog that the order has changed between R2012b and R2013b).

      In the end it’s not really important since my license manager will install (I’ve asked and we have the “maintenance service”) R2014a in the next couple of weeks. But it could be useful to know this color order for people that are unable to use a later version than R2012b.


    • Yair Altman says:

      The very latest default color order is this:

      >> get(0,'DefaultAxesColorOrder')
      ans =
                  0        0.447        0.741
              0.850        0.325        0.098
              0.929        0.694        0.125
              0.494        0.184        0.556
              0.466        0.674        0.188
              0.301        0.745        0.933
              0.635        0.078        0.184
    • Philippe Roy says:

      Thanks! :)

  49. Hi Yair Altman,
    The “hAxes.YRuler.SecondaryLabel.String” does not seems to work in R2014b. Do you know to change the label?

    hFig = figure('pos',[100,100,300,250]);
    x = -10:0.1:10;y = 1e7*sin(x)./x; 
    hAxes = gca;
    hAxes.YRuler.SecondaryLabel.String = 'millions';
    • Yair Altman says:

      @Tobias – simply add the following after updating the SecondaryLabel.String:

      hAxes.YRuler.SecondaryLabel.Visible = 'on';

      For some reason, the Visible property is modified to ‘off’ when the String property is modified, I have no idea why… (internal bug perhaps?)

  50. Yaroslav says:

    I have noticed that some properties change their enumeration values between HG1 and HG2. For example the 'Orientation' field changes from 'top-right' to a simple 'topright' etc.

    On another notice, in some cases using HG2, the data-tips are created (and changed programmatically) faster. They have also a much richer data-tip display (using TeX syntax and notation). It seems that MathWorks makes some really good job under the hood…

  51. Pingback: Property value change listeners | Undocumented Matlab

  52. Michael says:

    The problem with not being able to save transparent lines in vector format has been solved in the 2014b pre-release. I can even copy a figure and paste it accurately into illustrator. Soooooooooo wonderful!

  53. Dennis says:

    Dear Yair,

    Thank you for solving my problem:

    I was experiencing very low frequency line updates on a windows 7 system running R2012b (32bit) and also on R2014a (64bit). I had a figure with two axes, one showing a fixed rgb image filling approx. Half the screen (one-to-one, no scaling) and the other showing a line (only two nodes) that was continuously updated in a loop by changing the xdata and ydata. With the image in place, the loop frequency dropped to some 8Hz, whereas without the image (cdata empty), the frequency was around 65Hz as could be expected.

    Similar behavior could be expected if the image were refreshed and scaled at every iteration, but this was not the case, at least not at the matlab code level.

    Matlab support told me to upgrade to the R2014b pre-release, in which this issue should be resolved.

    However, it seems running R2012b with -hgVersion 2 also solves the problem (at least it’s a big improvement).

    Thanks again!

    • Yair Altman says:

      @Dennis – I’m glad I helped.

      I’m a little disappointed that MathWorks support asks customers to upgrade to a new release (possibly costing extra money and requiring extra development), when they could have simply given you the out-of-the-box solution on your specific platform, unsupported though it may be. At the very least they could have told you about this and let you choose between the supported and unsupported alternatives. This is what I would expect a professional customer-oriented support person to do. But maybe I’m just being naïve.

  54. Julien says:

    Hg2 is for tomorrow! Il was to MATLAB EXPO today in Paris and Loren Shure announced that R2014b release was for tomorrow. After years of waiting the new graphic engine, here we are!

  55. Pingback: Customizing axes rulers | Undocumented Matlab

  56. Michael says:

    I had problems using fHG2Client in R2014b. Scanning the web was fruitless. Checking the TMW own code solved the problem by replacing

    rootPane = jFrame.fHG2Client;


    rootPane = javax.swing.SwingUtilities.getWindowAncestor(jFrame.getAxisComponent);

    For my purpose (calling setAlwaysOnTop() method), it works also for R2013b and R2007b, making the try/catch statements for fHG1Client obsolete.

  57. Johannes says:

    Dear Yair,

    Now that R2014b and HG2 are out in the wild I thought I give it a try.

    However using the engine to process large amounts of data (e.g. with a simple plot command) I realised that HG2 is dead slow. Did you also notice that? There is a thread over at Matlab central (http://in.mathworks.com/matlabcentral/newsreader/view_thread/337755) that also is dealing with the problem, but so far nobody found a solution.

    Maybe you would like to share your insights.


    • @Johannes – this is a known issue, that I even reported on this page. The best known workaround at this point is to ensure that you are using hardware acceleration rather than software emulation of OpenGL. You can check this with the opengl(‘info’) command (look for “Software: false”). If you’re using software emulation, upgrade your graphics device driver to the latest version, it might help.

    • Johannes says:

      Thanks Yair,

      Actually I had already ensured that hardware acceleration is enabled. Still the performance is real bad.
      Do you have an other suggestion to improve speed at this point? Otherwise I will have to stick to R2014a.

    • I suggest that you contact MathWorks and let them try to help you. If you discover anything useful let use know here – I’m sure that many users will be interested.

      Also, if MathWorks hear from enough people (like you) who cannot upgrade due to the problematic performance, perhaps they will allocate extra development resources to fix this problem.

  58. Ramiro Massol says:

    hi Yair
    I tried your latest upload of uicomponent on R2014b and it reports an error while adding components in a jcombobox. The code is the following:

    h=uicomponent('style','JComboBox',{1,pi,'text'},'editable',true); % editable drop-down
    h.javaComponent.addItem('text2');  % adding data to the drop-down post-creation

    and the error I got is:
    No appropriate method, property, or field javaComponent for class matlab.ui.container.internal.JavaWrapper.

    any idea how to solve this?

    • @Ramiro – you can use the 2-outputs variant of uicomponent:

      [hCB,jCB]=uicomponent('style','JComboBox',{1,pi,'text'},'editable',true); % editable drop-down
      jCB.addItem('text2'); % adding data to the drop-down post-creation
  59. Siddharth Dani says:

    Hi Yair,

    I have run into a seemingly peculiar situation with HG2 with an intern I am mentoring. He is running MATLAB 2014b that was installed in January 2014 on a windows 7 OS.

     graphicsversion(fig, 'handlegraphics');

    returns a “0” which I thought should indicate that HG2 is in fact running, but the figures and plots he is creating look like they are using the old graphics engine. I am not sure if I can post a screenshot in the comments, but the colors and the graphics definitely look like the old version. We tried creating plots on other computers in our team (both windows and macs), that had installed the same version of MATLAB from the same ISO file, and they all seem to have HG2 running properly.

    Is there something trivial we are missing?



    • graphicsversion(fig, 'handlegraphics')==false does indeed indicate that HG2 is in use. I’m not sure why it would fall back to using HG1 on your computer. Try creating a new figure with a very simple plot and see whether it still happens. Then contact MathWorks support to ask for their assistance.

  60. Pingback: Matlab R2014b and newer: freezeColors no longer needed | SciVision

  61. Aaron Kahn says:

    Hi Yair,

    I am a first time poster but I truly love your site and it has helped me solve many a problem.
    I am running R2014a. I’ve created a GUI that allows the user to select from several languages. In order to support Spanish, for example, I needed to use Latin characters supported by html. As you know, the push button string property does not support html, so I created a JLabel to fit over the button to allow html strings.

    The problem is, using HG1 I am still able to click anywhere on the button for its functionality, while in HG2 the portion of the button covered by the jLabel is not ‘clickable’.

    Do you know why there is a difference? And do you know a possible work around for this or a different method?


  62. Pingback: Lo que he aprendido: especificar opciones de inicio en Matlab | Onda Hostil

  63. sipsj11 says:

    Doesn’t need to be so complicated, in the new version of MATLAB can set the figure to full size easily by:

    fig.OuterPosition=[0 0 1 1];
    • @sipsj11 – you are very mistaken: first, the method of setting the figure’s position to [0 0 1 1] has existed forever, not just since HG2.

      Secondly, this method is NOT equivalent to true maximization of the window, which is achieved by clicking the relevant icon on the top-right of the figure. For example, it ignores (overlaps) the taskbar and also shows the window borders, which a truly-maximized figure doesn’t.

Leave a Reply

Your email address will not be published. Required fields are marked *