Search code examples
matlabplotlegendmatlab-figuretransparency

How to make Matlab legend show opaque plot symbols when scatter plot symbols are semi-transparent in the figure


I am trying to create a scatter plot cloud, of which I set the points are all "filled" and semi-transparent by setting "MarkerFaceAlpha=0.1". However, when I export the legend automatically, the point symbols are also the same semi-transparent and it is hardly can be seen in legend. Do we have an easy way to switch on/off the MarkerFaceAlpha?

Here is the code:

figure()
scatter(X1,Y1,16, [0.9290, 0.6940, 0.1250],"filled",MarkerFaceAlpha=0.1,DisplayName='A')
hold on
scatter(X2, Y2,16, [0 0.4470 0.7410],"filled",MarkerFaceAlpha=0.1,DisplayName='B')
hold off
legend(Location="southwest",Box="off")

In this figure, transparency is 0.1, while I want to show opaque color in legend, how can I do that?


Solution

  • You can dummy it, by setting HandleVisibility="off" to hide your actual scatter data from the legend, and then plot some NaN vs NaN series (so it won't show anything) with the same properties other than the default alpha of 1, which then works as your legend variables.

    You could tidy this up by making a little function which makes the dummy legend series with the same properties as a given "real" series of data, I'll leave that as an exercise...

    X1 = randn(10000,1); X2 = randn(size(X1));
    Y1 = randn(size(X1))+3; Y2 = randn(size(X2));
    figure()
    
    hold on
    
    scatter(X1,Y1,16, [0.9290, 0.6940, 0.1250],"filled",MarkerFaceAlpha=0.1,HandleVisibility="off");
    scatter(NaN,NaN,16, [0.9290, 0.6940, 0.1250],"filled",DisplayName="A");
    
    scatter(X2, Y2,16, [0 0.4470 0.7410],"filled",MarkerFaceAlpha=0.1,HandleVisibility="off");
    scatter(NaN,NaN,16, [0 0.4470 0.7410],"filled",DisplayName="B");
    hold off
    
    legend(Location="southwest",Box="off")
    

    plot