Search code examples
matlabplotrotationheatmapaxis-labels

Rotating axis tick labels in a heatmap plot


When I generate a heatmap plot on MATLAB 2018b, the x-tick labels are rotated automatically, but often with an angle that does not look pleasing to me.

I would like to hardcode that they should always be rotated at 90 degrees. Usually, this code would do the trick:

ax = gca;
ax.XTickLabelRotation = 90

or

xtickangle(90)

but both versions are not supported for a heatmap.

How can I manually rotate the XTickLables in a heatmap plot?


Reproducible example:

cdata = [45 60 32; 43 54 76; 32 94 68; 23 95 58];
xvalues = {'Small','Medium','Large'};
yvalues = {'Green','Red','Blue','Gray'};
h = heatmap(xvalues,yvalues,cdata);
xtickangle(90)

Solution

  • Indeed the HeatmapChart object does not support rotating the label, but, the internal Axes object does, and we can reach it using struct as follows:

    set(struct(h).NodeChildren(3), 'XTickLabelRotation', 90); % put instead of the last example line
    

    One caveat though: the heatmap chart is interactive (at least on R2019a), and clicking on any of the labels to sort the heatmap reverses this change (i.e. rotates the text back). If you need the interactivity and also the rotation, you would need to find the callback/event that gets executed and piggyback the rotation code onto it somehow. However, if you're creating a chart for export - this shouldn't be an issue.