MATLAB Answers

How to rotate legend in matlab 2019

42 views (last 30 days)
Hi, I would like to rotate the legend from horizontal layout to vertical layout, just as shown in the picture below. Could anyone share some experience about this?
Thanks for you coming help!

Accepted Answer

Sai Sri Pathuri
Sai Sri Pathuri on 10 Jul 2020
There is no direct function to rotate legends in graphs using MATLAB.
However, as a workaround we can manually rotate the legends. Please refer to the following example:
% create a sample plot
h1 = plot(1:5);
% add legend to the graph
[legend_handle, icons] = legend('Sample legend');
% disable the box around the legend object
set(legend_handle, 'Box', 'off')
% get the current position of the legend object
% assign the required position of the legend to a new variable
new_leg_pos=[.7 0.6 .2 leg_pos(4)+.2] ;
% Get current line data (horizontal line)
xd = icons(2).XData;
yd = icons(2).YData;
% Swap X and Y data for line (make vertical line)
icons(2).XData = yd;
icons(2).YData = xd;
% Rotate and reposition the text
icons(1).Position = [0.5 0.4 0];
% Adjust legend size to accomodate changes.


CHEN Jianghua
CHEN Jianghua on 11 Jul 2020
Thank you so much. Your code teaches me a lot.
Adam Wincukiewicz
Adam Wincukiewicz on 17 Oct 2020
unfortunately this code doesn't work in my case. Output says: Unrecognized method, property, or field 'XData' for class ''.
Error is here: xd = icons(2).XData;
Do you have any idea what to do?
Thank you for your time.
Walter Roberson
Walter Roberson on 17 Oct 2020
Adam Wincukiewicz: which MATLAB release are you executing in?

Sign in to comment.

More Answers (0)




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by