Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Matlab: How to keep all xTicks but xTicklabels just on every 6 xTicks?

I have created a graph with data from an Excel file. I need to keep all the xticks but the xticklabels to appear just on every 6 ticks. I have tried doing this:

tickStep=6;
Sheet=2;
filename='MyData.xlsx';
[~,xAxis]=xlsread(filename,Sheet,'A2:A60'); 
yAxis=xlsread(filename,Sheet,'B2:B60'); 
plot(1:numel(xAxis),yAxis) 
set(gca,'xtick',1:numel(xAxis)) 
set(gca,'xticklabel',xAxis(1:tickStep:numel(xAxis)))

Unfortunately it does not work as all the xticks are plotted, but the xticklabels appear upon each xtick instead of every 6th like I was trying to achieve. I have spent quite a long time thinking about the solution:-(. I need help. Thanks.

edit: I've included an image to help answer questions below: enter image description here

In relation to this post, would it also be possible that the xticks appear every 4 xticks instead of keeping all of them, at the same time that the xticklabels are plotted every 6 xticks?, not sure about this.

like image 935
Sarah Avatar asked Dec 23 '13 00:12

Sarah


1 Answers

You still need to enter an empty string (or empty cell) for the ticks that will have no label. You can do this by replacing the last line with these three lines:

xTickLabels = cell(1,numel(xAxis));  % Empty cell array the same length as xAxis
xTickLabels(1:tickStep:numel(xAxis)) = xAxis(1:tickStep:numel(xAxis));
                                     % Fills in only the values you want
set(gca,'XTickLabel',xTickLabels);   % Update the tick labels

Edit in response to questions below...

The reason your labels appear to be offset from the ticks is because the bottom of the letters appears to be getting lined up with the tick mark. I'm guessing you want the text justified such that the center of each letter lines up with the tick mark. There's no way to do this with the standard MATLAB axes, but there are some submissions on the MathWorks File Exchange that convert the tick labels to text objects and thus give you more options for customizing the text properties:

  • XTICKLABEL_ROTATE by Brian Katz
  • Format Tick Labels by Alexander Hayes

Once you convert the labels to text objects, you can then adjust the rotation or vertical justification by modifying the 'Rotation' and 'VerticalAlignment' properties, respectively.

like image 131
gnovice Avatar answered Oct 29 '22 16:10

gnovice