Plot markers transparency and color gradient

Last week I explained how to customize plot-lines with transparency and color gradient. Today I wish to show how we can achieve similar effects with plot markers. Note that this discussion (like the preceding several posts) deal exclusively with HG2, Matlab’s new graphics system starting with R2014b (well yes, we can also turn HG2 on in earlier releases).

As Paul has noted in a comment last week, we cannot simply set a 4th (alpha transparency) element to the MarkerFaceColor and MarkerEdgeColor properties:

>> x=1:10; y=10*x; hLine=plot(x,y,'o-'); drawnow;
>> hLine.MarkerFaceColor = [0.5,0.5,0.5];      % This is ok
>> hLine.MarkerFaceColor = [0.5,0.5,0.5,0.3];  % Not ok
While setting the 'MarkerFaceColor' property of Line:
Color value must be a 3 element numeric vector

Standard Matlab plot markers

Standard Matlab plot markers

Lost cause? – not in a long shot. We simply need to be a bit more persuasive, using the hidden MarkerHandle property:

>> hMarkers = hLine.MarkerHandle;  % a object
>> hMarkers.get
    EdgeColorBinding: 'object'
       EdgeColorData: [4x1 uint8]
       EdgeColorType: 'truecolor'
    FaceColorBinding: 'object'
       FaceColorData: [4x1 uint8]
       FaceColorType: 'truecolor'
    HandleVisibility: 'off'
             HitTest: 'off'
               Layer: 'middle'
           LineWidth: 0.5
              Parent: [1x1 Line]
       PickableParts: 'visible'
                Size: 6
               Style: 'circle'
          VertexData: [3x10 single]
       VertexIndices: []
             Visible: 'on'
>> hMarkers.EdgeColorData'  % 4-element uint8 array
ans =
    0  114  189  255
>> hMarkers.FaceColorData'  % 4-element uint8 array
ans =
  128  128  128  255

As we can see, we can separately attach transparency values to the marker’s edges and/or faces. For example:

hMarkers.FaceColorData = uint8(255*[1;0;0;0.3]);  % Alpha=0.3 => 70% transparent red

70% Transparent Matlab plot markers

70% Transparent Matlab plot markers

And as we have seen last week, we can also apply color gradient across the markers, by modifying the EdgeColorBinding/FaceColorBinding from ‘object’ to ‘interpolated’ (there are also ‘discrete’ and ‘none’), along with changing the corresponding FaceColorData/EdgeColorData from being a 4×1 array to a 4xN array:

>> colorData = uint8([210:5:255; 0:28:252; [0:10:50,40:-10:10]; 200:-10:110])
colorData =
  210  215  220  225  230  235  240  245  250  255
    0   28   56   84  112  140  168  196  224  252
    0   10   20   30   40   50   40   30   20   10
  200  190  180  170  160  150  140  130  120  110
>> set(hMarkers,'FaceColorBinding','interpolated', 'FaceColorData',colorData)

Matlab plot markers with color and transparency gradients

Matlab plot markers with color and transparency gradients

This can be useful for plotting comet trails, radar/sonar tracks, travel trajectories, etc. We can also use it to overlay meta-data information, such as buy/sell indications on a financial time-series plot. In fact, it opens up Matlab plots to a whole new spectrum of customizations that were more difficult (although not impossible) to achieve earlier.

Throughout today, we’ve kept the default FaceColorType/EdgeColorType value of ‘truecolor’ (which is really the same as ‘truecoloralpha’ as far as I can tell, since both accept an alpha transparency value as the 4th color element). If you’re into experimentation, you might also try ‘colormapped’ and ‘texturemapped’.

Categories: Handle graphics, Medium risk of breaking in future versions, Stock Matlab function, Undocumented feature

Tags: , , , ,

Bookmark and SharePrint Print

49 Responses to Plot markers transparency and color gradient

  1. Paul says:

    Thanks, this is useful — setting an alpha component is a better way to visualise density than applying jitter.

  2. Grunde says:

    Is it possible to make the area plots transparent? Or do I have to use the patch command?

    • Yair Altman says:

      @Grunde – Yes this is possible, but I don’t think you need to use any undocumented features for this. Assuming you used the builtin area function to generate the plot, you can set the FaceAlpha property of the area-plot’s children.

      Alternatively, you can use the builtin alpha function.

    • Grunde says:

      The area object doesn’t have any children. And the area object itself doesn’t have a FaceAlpha property. At least in 2014b.

    • Yair Altman says:
      h = area(magic(4));  drawnow;  % 1x4 area object
      set([h.Face], 'ColorType', 'truecoloralpha')
      h(2).Face.ColorData(4) = 90;  % =90/255=35% opaque =65% transparent
    • Guenter says:

      Dear Yair,

      For some reason on Matlab 2014b the area alpha doesn’t seem to work. I copy/paste your sample and run it. Although it doesn’t throw any error, it seems to ignore the settings in h(2).Face.ColorData(4). I can change it to whatever value, but the transparency of the faces (areas) don’t change at all.
      Am I missing something?

    • It works for me… Perhaps you are using software emulation (not hardware acceleration) in your opengl. Type opengl(‘info’) to find out.

    • Guenter says:

      Dear Yair,

      Thanks for you reply. I did some further tests and I think I found at least one problem. When I run the area command within a loop for plotting multiple sets of data into one plot it sometimes happens that the x-axis is resized to fit the data. Whenever this command is called the previous settings are discarded and all areas have the same color and no transparency. Can you confirm that using e.g.

      h = area(magic(4));  drawnow;  % 1x4 area object
      set([h.Face], 'ColorType', 'truecoloralpha')
      h(2).Face.ColorData(4) = 90;  % =90/255=35% opaque =65% transparent
      xlim([1.5 2.5])

      breaks the settings for transparency?

    • Guenter says:

      Hi Again,

      So, finally I figured it out how to circumvent the problem with the resizing. I simply had to apply the color and alpha settings at the very end of my plotting script (after settings xlims, adding legends, etc.). Then this works just fine.
      Thanks again for your kind help and for putting this down for others to read!

  3. Michael says:

    As far as I can tell, changing the EdgeColorBinding (or FaceColorBinding) from ‘object’ to ‘interpolated’ or ‘discrete’ is problematic. Entering Edit Plot mode (the pointer icon on the toolbar) resets the ColorBinding and ColorData back to ‘object’ and the original color.
    Short Example:

    x = 1:10; y= 1:10;
    pl = plot(x,y,'*');
    drawnow; % Otherwise pl.MarkerHandle gives me GraphicsPlaceholder objects
    hmarkers = pl.MarkerHandle;
    oldcolordata = hmarkers.EdgeColorData;
    newcolordata = uint8(repmat(oldcolordata,1,numel(x)));
    newcolordata(:,1) = [255;0;0;255]; % Turn the first marker red
    hmarkers.EdgeColorData = newcolordata;
    hmarkers.EdgeColorBinding = 'discrete';

    This will generate a simple line with the first point red. Clicking the Edit Plot icon will reset all markers.

    • Leonardo M. says:

      Even without changing EdgeColorBinding/FaceColorBinding from ‘object’ to ‘interpolated’ or ‘discrete’, the original color is reset back to the original color if a legend is added to the plot:

      hLine.MarkerFaceColor = [0.5,0.5,0.5];
      hMarkers = hLine.MarkerHandle;                    % a object
      hMarkers.FaceColorData = uint8(255*[1;0;0;0.3]);  % Alpha=0.3 => 70% transparent red
      legend('show');                                   % ! This will reset back the original color.

      Does anyone have a solution for this?

    • Fabian says:

      Unfortunately, the same happens even when hitting ‘Edit’ -> ‘Copy Figure’ or trying to export it. I built a bunch of pretty figures with this but they are stuck within Matlab :-(

    • You can try to place your customization code in a short function that you’d reference in the axes CreateFcn property and/or its MarkedClean event (using addlistener).

    • Fabian says:

      Yup, that works. Thanks so much, Yair. It’s a pretty awful hack job to achieve what I feel should be basic functionality but here we go:

      % generate data
      xData = normrnd(1, 0.2, 1000, 1);
      yData = normrnd(1, 0.2, 1000, 1);
      % plot and make transparent
      ha = plot(xData, yData, 'ko');
      hm = ha.MarkerHandle;
      cFace = uint8(255*[0 0 1 0.1])';
      cEdge = uint8(255*[0 0 0 0.3])';
      hm.FaceColorData = cFace;
      hm.EdgeColorData = cEdge;
      % keep transparent
          @(ObjH, EventData) keepAlpha(ObjH, EventData, cFace, cEdge));

      and the keep function:

      function keepAlpha(src,eventData, FaceColor, EdgeColor)  
          hm = src.MarkerHandle;
          hm.EdgeColorData = EdgeColor;
          hm.FaceColorData = FaceColor;   

      Note that when adding a legend the symbol comes up wrong. But at least I can export my scatter plots now…

  4. Claire O. says:

    Thanks for all the useful tips. I have a nitpicky question: when I change any hidden property of my figures I have to manually select the line of code and execute it by itself (sometimes I have to repeat this twice before it works). It will not just execute itself if I run it as a script or a function. Any idea why that is?

    • @Claire – it should work in a script/function as well. You are probably doing something wrong. Perhaps the figure is not visible when it reaches that line of code, or maybe you just need to add a pause(0.1) and/or drawnow before your property-modification line.

    • Claire O. says:

      @Yair, I just saw your response. Thanks so much, adding the drawnow did the trick!

  5. Fabian says:

    Thanks for writing this post. I find transparent markers really essential for making dense scatter plots readable. However, when I run your code (see below), hMarkers is empty. I use 2014b on Win8. Any idea what’s going wrong?

    x=1:10; y=10*x;
    hMarkers = hLine.MarkerHandle;  % this is fine but returns a 0x0 empty GraphicsPlaceholder array
    hMarkers.get % hence this does nothing
    hMarkers.FaceColorData = uint8(255*[1;0;0;0.3]);  % this fails
  6. luc says:


    I’m trying this in matlab r2015a, I got the same problem as Fabian, but the drawnow command does not solve the problem.

    x_new3=nan; y_new3=nan; z_new3=nan;
    hMarkers = threednumeric3.MarkerHandle;  % a object
    hMarkers.FaceColorData = uint8(255*[1;0;0;0.3]); % Alpha=0.3 => 70% transparent red
  7. Philip says:

    Hey Yair,

    thank you very much for these very valuable tips! They really open up a plethora of charting options that come in very handy, in my case.

    Do you have any further details / documentation about ‘MarkerHandle’? For example, I am wondering about how to use the xxBinding properties; how exactly do ‘object’, ‘interpolated’, ‘discrete’ and ‘none’ work?

    One more question: in MATLAB, I frequently need to generate a 2D scatter plot with:
    (1) use individual marker transparencies to encode a 3rd variable (e.g. age of people). Your post solves this :-)
    (2) use individual marker sizes to encode a 4th variable (e.g. number of people). I’m stuck here: I do not know of any possibility to vary the marker sizes individually. While there are appropriate object properties (Size for the Line class, and MarkerSize for the MarkerHandle class), these are apparently required to be scalars.
    I’d love to set these to a vector. For performance reasons, I would like to avoid calling ‘line’ several times in a loop.
    Do you have any idea or suggestion?

    Thank you very much!

  8. Priyanka says:

    Thanks for this useful tip! I’m still finding my way around MATLAB, and unfortunately I’m stuck – was wondering if I can access the hidden MarkerHandle in Matlab 2013a? Not able to find any documentation on this. Thanks for any help.


  9. Dani says:

    The keepAlpha of Fabian does a good job preventing Matlab to get rid of the transparency again when, e.g., legend is called. Is there a way to convince ‘legend’ to show the transparent markers properly too?

    • Hi Dani and Yair,
      I have been using the keepAlpha trick with success as well to keep transparency on the figure Markers when toggling the legend. I am, as Dani, very keen to find a solution to keep the transparency in the legend markers as well.
      Any hint into where to look for a begining of solution would be very welcome. For example, is there a hidden way to access the handles to the Markers that are in the legend ? Would the optimal solution be to create a function myLegend that would design the legend from scratch ?

    • @Dani & @Christopher:

      The legend function clears marker customizations such as transparency. You can restore the transparency by re-updating hMarkers.FaceColorData following the legend call.

      In order to customize the legend itself, we need to dig into the legend object’s hierarchy. This is not too difficult:

      hLegend = legend('on');
      hMarkers.FaceColorData = uint8(255*[1;0;0;0.3]);  % Alpha=0.3 => 70% transparent red  - restored after the legend call
      hLegendComponents = hLegend.EntryContainer.Children;  % hLegendComponents has 2 children: child 1 = LegendIcon, child 2 = Text (label)
      hLegendIconComponents = hLegendComponents.Icon.Transform.Children;  % child 1 = Marker, child 2 = LineStrip
      hLegendMarker = hLegendIconComponents.Children(1);
      hLegendMarker.FaceColorData = uint8(255*[1;0;0;0.3]);  % Alpha=0.3 => 70% transparent red


  10. EZ says:

    Hi Yair,
    Thank you for the terrific post! I have a question on printing figure to pdf (or any format really!) and retaining the transparency. It used to be that zbuffer would do the trick (loses vector format) but at least the transparency property is not lost. In >2014, zbuffer is no longer an option. I was wondering if you have had any success in using other renderers? Thanks again.

    • @EZ – transparency output is (and always was) problematic in Matlab. In general, painters does not render transparencies so in HG2 (R2014b onward) we need to use the slower opengl renderer for export. Try using print -dpdf and/or the export_fig utility. You’ll probably still run into limitations with either of these though.

  11. Carl Witthoft says:

    (sorry about directly emailing – I missed your warnings)
    Hi – re your column on assigning transparency to plot markers: I tried the code on a simple example and all was well. Then I tried a tight loop, plotting a single point at a time (doing this to assign a different color to each point in the graph), and invariably within a few loop cycles, when I grab the “plothandle.MarkerHandle”, it’s empty. In these cases, the class of this empty object is “”
    while when the operation is successful, the class is:

    I’ve tried things like clearing variables every loop, putting in a delay timer, and so on, with no luck. Any idea what’s going on?
    many thanks

  12. ACenTe says:

    Great article, it was very helpful.

    I found an issue, though I don’t think it’s related to this method “per se”. When I try to export the figure, the transparency of the markers is lost, but the transparency of other objects is kept (for example, patches).

    Is there a solution for this? or any way to export the figure exactly as it’s shown in the Figure window?

    I’m using 2014b and I’ve tried exporting to png and pdf using both the painter and the OpenGL renderers with similar results.

  13. Nasser says:

    The above does not work on Matlab 2016a. I get no transparency at all.
    >> ver
    MATLAB Version: (R2016a)
    MATLAB License Number: STUDENT
    Operating System: Microsoft Windows 7 Home Premium Version 6.1 (Build 7601: Service Pack 1)
    Java Version: Java 1.7.0_60-b19 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode

    x=1:10; y=10*x; hLine=plot(x,y,'o-'); drawnow;
    hLine.MarkerFaceColor = [0.5,0.5,0.5];
    hMarkers.FaceColorData = uint8(255*[1;0;0;0.3]);

    The dots are still the same color. No transparency. Nothing changed.

    • @Nasser – this is because you did not read carefully, and so you missed 3 important commands!

      x=1:10; y=10*x; hLine=plot(x,y,'o-'); drawnow;
      hLine.MarkerFaceColor = [0.5,0.5,0.5];
      drawnowhMarkers = hLine.MarkerHandle;hMarkers.FaceColorType = 'truecoloralpha';hMarkers.FaceColorData = uint8(255*[1;0;0;0.3]);
  14. Lukas K. says:

    Hi! I’m would like to get a better view of many points in a scatter3 plot, but unfortunately the transparency is lost once I rotate the plot. Is there a way to fix that?

  15. Paweł says:

    Is it possible to do with point cloud plot command: pcshow();? I want to change size of Brushing marker.
    I get this:

    >> drawnow
    >> hMarkers = hLine.MarkerHandle;
    No appropriate method, property, or field 'MarkerHandle' for class ''.

    I’ve been looking into hidden lines, axes properties, but I can’t find it anywhere.

  16. Marconi Barbosa says:

    Sweet. But when I try to print, Matlab2014b clears everything. I created events listeners for markers in both plot and legends. That works fine to rebuild after a click in ‘show plot tools’; but won’t work in print preview… 😐

    • @Marconi – this has already been reported by others on this blog. Matlab’s print and saveas functions clear such transparencies, and there is no known workaround for this. You can use a screen capture utility to capture the actual appearance and then print from that screen-capture.

    • Anon says:

      Use MATLAB2015b! It will print transparencies correctly.

  17. Anon says:

    I found that when I upgraded to Matlab 2016a, the transparency functions will generate figures in the correct way but will not print the transparencies. Importantly, 2015b prints figures properly!

  18. LucyK says:

    Thank you so much for this page, it is fantastic! I finally have my transparent scatter plots back in 2015a!

    • LucyK says:

      PS I found a workaround to save transparency changes in matlab 2015a: if you use saveas to save the file as *.svg, then open in Inkscape (free) and export as a png there, transparency values are saved.

      I also found I needed to build in a brief pause in my script before obtaining the marker handle to avoid getting the following error: “Too many outputs requested. Most likely cause is missing [] around left hand side that has a comma separated list expansion.“. Reading back, it looks like another user has also mentioned this – pause(1) (shorter is possibly fine too) resolved the error.

Leave a Reply

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