Search code examples
matlabboxplot

Colorfill the boxes in a boxplot in Matlab


Is there a way to fill the boxes in a boxplot in Matlab?

I was able to change the color of the boundaries of the boxes using the colorgroup option of the boxplot function (http://www.mathworks.com/help/stats/boxplot.html), but could not find any option to change the or fill the color of the space inside box itself.

Edit: So, I went through the code at the link (http://www.mathworks.com/matlabcentral/newsreader/view_thread/300245) pointed out user1929959 in the comments. However, i am new to Matlab and I would really appreciate a brief explanation of what the code does. Here is the code from that link:

load carsmall
 boxplot(MPG,Origin)
 h = findobj(gca,'Tag','Box');
 for j=1:length(h)
    patch(get(h(j),'XData'),get(h(j),'YData'),'y','FaceAlpha',.5);
 end

I am also open to other solutions. Thanks.


Solution

  • With FINDOBJ function you search for graphic objects with tag equals to 'Box' in the current axes (gca = get current axis handle).

    Tags for all objects in boxplot you can find in the official MW documentation (just before examples): http://www.mathworks.com/help/stats/boxplot.html

    FINDOBJ returns handles to all objects it found into variable h, which is double array. You use the handle to modify the object properties. You can see all properties for a given handle with get(h(1)) or inspect(h(1)).

    For example you can set line width:

    set(h,'LineWidth',3)
    

    Since box is a line object it doesn't have FaceColor or FaceAlpha (transparancy) properties as for patch, so you cannot color it directly. You have to draw patches over it with yellow color (set by 'y' parameter) and 0.5 transparancy. You get XData and YData properties to get the patch coordinates. See here for all patch properties.

    Again if you don't know what some function does, always check matlab documentation with help function_name or doc function_name.