File Exchange

image thumbnail

XTICKLABEL_ROTATE

version 1.3 (10.5 KB) by

Rotate XTickLabel to better accommodate long labels and text labels.

4.44444
73 Ratings

154 Downloads

Updated

View License

Editor's Note: This file was a File Exchange Pick of the Week

A modified version of XTICKLABEL_ROTATE90, this version allows for arbitrary angle rotation and most importantly the use of text labels. In addition, an attempt is made to adjust the size and placement of the axis and xlabel to accommodate the new labels.
  Example : %Use text labels rotated 45° without tex interpreter
   boxplot(randn(5,5),1)
   xticklabel_rotate([1:5],45,{'label_1','label_2','label_3','label_4','label_5'},'interpreter','none')

Comments and Ratings (105)

Brian Katz

Brian Katz (view profile)

Linhong, as stated, it seems like you tried to run xticklabel_rotate twice on the same figure/axes, which is not possible. clear figure/axis, plot and run again.

Brian Katz

Brian Katz (view profile)

See Michelle's comment (6-Mar-2015): This function should be obsolete; as of R2014b, MATLAB now has the built-in ability to rotate tick labels.
     set(gca,'XTickLabelRotation',45)
Of course for those working with older versions at times, it still comes in handy... :)

Lihong Ren

Error using xticklabel_rotate (line 86)
xticklabel_rotate : can not process, either xticklabel_rotate has already been run or
XTickLabel field has been erased
why?

Bob's fix (30 Nov 2016) works well in R2017a

Pascal R

It seems to be shifting my Xticklabel, creating an offset between the stemplot (or barplot) and the Xticklabels. So eventually, the labels and bars are staggered.

Otherwise, it works well.

Donghoon Yeo

nice work thanks :)

Bob

Bob (view profile)

Great Utility but this fails as of R2016b due to the following line:

if ~exist('xTickLabels')

This should be changed to:

if ~exist('xTickLabels','var')

The reason is because there now exists a file named xticklabels:

>> which xTickLabels
C:\Program Files\MATLAB\R2016b\toolbox\matlab\graph3d\xticklabels.m

The old statement will always return true regardless of whether the local variable exists or not, resulting in the following error:

Undefined function or variable 'xTickLabels'.

Error in xticklabel_rotate (line 124)
if length(XTick) ~= length(xTickLabels),

Replacing the line to add the var qualifier checks only for variables and resolves the issue:

if ~exist('xTickLabels','var')

saeid safaei

Yanbing Jia

jhlasheras

working grate in 2012a. Cheers

chlor thanks

I used this line in my GUI and my axes shrinked and shifted, fyi...

praveen sagar

i am using matlab 2013a ,how to fit this code in my m.file i am a new user using file exchange i want my xTick label to rotate +45 .

This code is still useful when a user has a version lower than 2014b. Overlap issue can be resolved by first having right size of figure and then using this function. But one problem I am experiencing with the code is that sometimes when it is used in subplot, the overlap issue happens again in only last subplot.

Andrea

Andrea (view profile)

When putting labels on top and rotating them by a negative angle they overlap with the figure. Can someone help me to solve this?

Jannis Reich

Michelle Hirsch

Great news to fans of XTICKLABEL_ROTATE - as of R2014b, MATLAB now has the built-in ability to rotate tick labels (X, Y, and Z). You can control tick label rotation through the axes properties XTickLabel, YTickLabel, and ZTickLabel.

Ex:
plot(1:3)
ax = gca;
ax.XTickLabelRotation = 45;

Huge thanks to Brian for serving the MATLAB community with this great submission since 2003!

pr

pr (view profile)

I am using 'plotyy' to interpret the data and date/time on x-axis. With the help of this function the labels are rotated successfully. It looks great when the figure is exported. But the 'linkaxes' property for any kind of plot doesn't work. How to solve this issue?

downloaded
xticklabel_rotate([],90,any_label)
works perfect
thanks

Brian Katz

Brian Katz (view profile)

@Moroni : Please look at the help for the correct usage, as you are not using the function correctly.

For your example, simply use:
  bar(1:5,1);
  xticklabel_rotate([],45,stock_labels)

Moroni

Moroni (view profile)

I am getting this error everytime
Undefined function 'xticklabel_rotate' for input arguments of type 'double'.

stock_labels = {'Market','3M','ALCOA','ALTRIA','Amex'};
bar(1:5,1);
set(gca(),'XTick',1:31)
set(gca(),'XTickLabel',stock_labels,'XGrid','on');
xticklabel_rotate(gca,45);

help please!

Brian Katz

Brian Katz (view profile)

Experience has shown that this function doesn't handle a lot of resizing, which in Matlab can often change axis limits and ticks.
It is best to run it just before exporting, and it is highly recommend to export/print without resizing.

Simon

Simon (view profile)

Ivan

Ivan (view profile)

Ivan

Ivan (view profile)

Erik

Erik (view profile)

Sabri Mutlu

The script does not work in the sense that often the labels are not alligned, at least when saving a graph or when scaling a graph. rotateXLabels.m in http://www.mathworks.com/matlabcentral/fileexchange/27812-rotate-x-axis-tick-labels/all_files works fine for us instead.

MoonKnight

Krishna

There might be small glitch,while using this rotation on a bar graph with positive and negative variations and long texts for ticks, a part of the labels ended up being positioned inside the graph. :(

when using a pareto chart which has two yticks, the yticks on the left stay the same but the yticks on the right get moved so they no longer align with the data.

Masatoshi

Faezeh Safari

It works great with the xticklabel rotation! But, when I save my matlab figure as pdf the pdf file contains rotated version of my matlab figure. I have double check everything and found this function is the cause. I will appreciate if anybody can help me with this.

Shahar Shlomi

Thanks so much!
I've downloaded the file and simply added xticklabel_rotate to my code. Magic!

ted p teng

ted p teng (view profile)

Julian

Julian (view profile)

Haven't worked it hard - seemed to do what I needed out of the box - so thanks very much.

Ziv

Ziv (view profile)

just what i needed. few minor issues but got the hang of it in no time.
Ziv yekutieli

Boi-Yee Liao

 thank you

gda

gda (view profile)

When I'm calling for xticklabel_rotate function I'm getting the error
??? Error using ==> xticklabel_rotate at 78
xticklabel_rotate : can not process, either xticklabel_rotate has already been run or
XTickLabel field has been erased

Can anyone help me? thanks

Minli

Minli (view profile)

this helps a lot. thank you !!

Corinne

Pepa

Pepa (view profile)

Brian Katz

Brian Katz (view profile)

I have examine the issue mentioned by Denzel Li. I have tried to reproduce the errors mentioned with only small sucess. I have found an issue with the axis position being changed when y-labels are on the right, which I will look into. I do not get such notable misalignements as you have shown when I run the same examples, so I am not sur how to respond. Please verify that these issues exist when you PRINT the figure, and it is not a simple figure screen display issue.

The text boxes are created at the tick positions, in data units. They are middle aligned, there is not much more that can be done, but I am open to suggestions.

Brian Katz

Brian Katz (view profile)

It seems that the problem seen by Daniel Visser is related to the newer version of boxplot. I am not currently running v.2010 so I cannot examine this issue further at this time. Sorry.

m s

m s (view profile)

thanks a lot.

it works!! will save a lot of my time!!! yay!!!!

Lindsey

??? Error using ==> xticklabel_rotate at 117
xticklabel_rotate : must have same number of elements in "XTick"
and "XTickLabel"

I have checked that I have 29 ticks and 29 labels

Denzel Li

XTICKLABEL_ROTATE is a wonderful tool. Thanks a lot for making it available. How ever, I had the same problem as mentioned by Theresa above, which results in figures hard to use for publish. I also described this issue in great detail on stackoverflow:

http://stackoverflow.com/questions/4763673/problem-or-bug-in-xticklabel-rotate-while-drawing-heatmap-and-rotating-xtick-labe

Please take a look and any suggestion will be highly appreciated.

Ian

Ian (view profile)

I got the following error when running just xticklable_rotate():
Warning: Error occurred while evaluating listener callback.
> In axis>LocSetLimits at 208
  In axis at 94
  In plotPhases3 at 46
??? Error using ==> set
Values must be finite and non-NaN

The function works fine when there is a single plot, maybe this is because I am using subplots?
I would really like if this function worked.

Julian

Julian (view profile)

Thanks very much, handy utility (I've not tried working it hard - seemed to do what I needed out of the box)

Daniel Visser

Hi! Cool stuff!
Unfortunately I Have the same problem as ander and bob with:
figure; boxplot(rand(2));
set(gca,'xtick',[1 2],'xticklabel',{'Tick1' 'Tick2'})
xticklabel_rotate()
%matlab version: 7.10
The error starts at line 160: set(gca,'units','pixel')!?! (Why does the change of unit change the axis size?)
Nevertheless: Thank you so far

Nick Mariette

Nice one. Just what I needed. Thanks Brian!

Brian Katz

Brian Katz (view profile)

Please note that, as stated in the function and the error message above, XTickLabel_Rotate CANNOT be called multiple times on the same plot. Calling a new figure, the example works fine.

Li

Li (view profile)

The example does not work:
boxplot(randn(5,5),1)
   xticklabel_rotate([1:5],45,{'label_1','label_2','label_3','label_4','label_5'},'interpreter','none')
??? Error using ==> xticklabel_rotate at 71
xticklabel_rotate : can not process, either xticklabel_rotate has already been
run or XTickLabel field has been erased

Aaron

Aaron (view profile)

Useful, but labels are offset (as are titles) when using multiple subplots (specifically, a 2x2 array of subplots).

Diego Barragán

Diego Barragán (view profile)

Benjamin

a fast and easy solution is to comment

set(gca,'position',newpos) ;

and, if necessary, set the new position manually

for me, with a few changes, it works very well

Benjamin

I have the same Problem

Error in ==> xticklabel_rotate at ...

Seems to be a problem because I changed the XAxisLocation to 'Top'

I will check if there is a simple solution if there is solution yet.

Theresa

Another update: when you rotate the labels they're not always lined up with each other. Super annoying and makes the figure unusable for publication....which makes the function pretty much useless to me. Sorry...seems like a good start but I've encountered too many small annoying bugs that make the figures publication unfriendly.

bob

bob (view profile)

Problem, same as les ander:

 ??? Error using ==> set
Width and height must be > 0.

Error in ==> xticklabel_rotate at 168
set(gca,'position',newpos) ;
 

any help?

thx

Tove

Tove (view profile)

Theresa

Another update: using the full command works with rotations of 90 degrees for me.

i.e. xticklabel_rotate([], 90, []) works well, but xticklabel_rotate does not work. Now that I can use the full functionality of this nice program I want to update my original rating.

Theresa

Unfortunately, I have not had the success of others with this file. When it rotates the labels, it overlays them onto the plot so they are half over the x-axis and data, and half where they should be. It looks horrible and I can't use the figures that way.

Update: The bug is in rotating 90 degrees. Other rotations work OK. But it's annoying to not have full rotation functionality.

Salifou

Great Function. Thanks a bunch! It saved me from caving in to Stata.

Gilles Criton

Thank you very much, so useful !

Etsuko

Etsuko (view profile)

Fredrik

Tue

Tue (view profile)

THanks... tens of boxplots to process. Not automated thanks to this script.

flicker 420

Thanks..Nice work

M Shaw

Very helpful and well documented. Thanks!!

Peter Pan

Sorry,
but this rating system is confusing.

The function is perfect, just a small buck.

Peter Pan

Nice function, thanks a lot!

There is a small error, it occurs just when only one XTickLabelName is given.

For example:
bar( [ 1 ] ); xticklabel_rotate;

It claims on line 160, cause get(htext, 'extent' ) gives no cell, but an array back.
My solution:
x = get( hText, 'extent' );
if iscell( x ) == true
    textsizes = cell2mat( x ) ;
else
    textsizes = x;
end
with line 160 deleted works.

Any,
   Thanks!

Korey Y

Great function. I had to place my X-axis labels at the top and therefore have them left-aligned so I added a few lines somewhere around line 141:

xAxisLocation = get(gca, 'XAxisLocation');
if (xAxisLocation == 'top')
    set(hText,'Rotation',rot,'HorizontalAlignment','left',varargin{:})
else
    set(hText,'Rotation',rot,'HorizontalAlignment','right',varargin{:})
end

Chris Lowis

Brilliant, solved my problem with a single function call using the default options.

David K

Excellent utility. It almost needs to be part of matlab. This is so essential.

Natalia Rivera

This is really helpful. Thank you!

Patrick Freeman

Very useful function for displaying long labels. Good job!

Brent Bergan

As soon as you zoom in, the tick labels do not follow appropriately. Too bad, this would have been a great function

Greg Heins

Awesome - worked first time - like the TeX ability.

Greg Heins

Awesome - worked first time - like the TeX ability.

George C

just when i was about to switch to excel, i found this! MATLAB rocks!!

Nathan Pust

Very helpful code.
if lines 68-77 are changed to as follows, the code will allow the current text labels to be used and property value pairs to be changed for those labels. Example usage:

xticklabel_rotate([],45,[],'Fontsize',14)

Lines 68-76:
if (nargin < 3 || isempty(varargin{1})) & (~exist('XTick') | isempty(XTick)),
    xTickLabels = get(gca,'XTickLabel') ; % use current XTickLabel
    % remove trailing spaces if exist (typical with auto generated XTickLabel)
    temp1 = num2cell(xTickLabels,2) ;
    for loop = 1:length(temp1),
        temp1{loop} = deblank(temp1{loop}) ;
    end
    xTickLabels = temp1 ;
    varargin = varargin(2:length(varargin));
end

Stanley Bileschi

works exactly like I wanted it to

Brian Katz

I have re-tested this with changing fonts in the original call and also afterwards via the handle, with no problems...

Shai Shen-Orr

If you try setting to a different font through XTickLabel_rotate function call or after the labels has been set - the entire axis is messed up.

Fangwen Lu

It's cool!

Kay Pham

This is really useful! GREAT!

Kay Pham

This is great! It's really useful! Thanks.

Malik Yousef

When i use your code on 4 subplots i get weird results whne one of them that has different axis.
And i see that the subplot become so small!!
How to overcome this problem

Isabella Osetinsky

Thank you. Solves many problems!
Add "set(gca,'tickdir','out')" to point out the label location.

mark drever

this was sweet.

les ander

??? Error using ==> set
Width and height must be > 0.

Error in ==> xticklabel_rotate at 168
set(gca,'position',newpos) ;

Prasanth Karumanchi

awesome stuff

Yuval Cohen

Other than the zoom issue, perfect. BRAVO!

Brian Katz

As this operation removes the current labels and places text objects a tthe appripriate place in the figure window, there is no dynamic link to the axis afterwards, making zoom response difficult. Until MatLab integrates this type of behavoir directly into the label properties I think it would be very difficult to include dynamic behavior.

K H

For this and similar functions where text replaces ticks, is there a way to make it react to zooming?

Anshuman Bansal

Well Done!
I was struggling with this issue since last couple of months! Trying to write my own unsuccessful code..! Saved me a lot of time! I guess it should be part of standard MATLAB package

Imola Fodor

Awesome. Thanks!

Alf Magnusson

You made my day (nigth) Thanks

John Godward

I spent some time looking for standard Matlab functions to do this with no luck. Then I found this m-file which did what was required. Thanks.

David Sterling

Nicely done! Now I don't have to rotate my plotting axis(eg. barh and horizontal boxplot) to handle the long strings that inevitably creep into my categorical tick labels.

Martin Schaefer

You saved me from using Excel for a whole bunch of Bargraph plots.
Thanks very much for that.
Another nice option would be to edit the ticks freely, that means to allow 2 line ticks and things alike

Updates

1.3

2014 : Allow for multiline labels

1.2

Rev.2010. Revisions made to improve functionality in response to various user recommendations.

1.1

Use suggested modifications have been integrated. The current version now support TOP xlabels. In addition, the degree of resizing of the axis has been reduced.

Update 11-jun-03 : Resizing of axis is improved with control of xlabel,ylabel, and title. Improved default codition works with PREDEFINED XTickLabels now.

MATLAB Release
MATLAB 7.4 (R2007a)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video