Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace x-axis in a Matlab figure?

What commands do I need to shift the x-axis values in an open Matlab figure without affecting the y-axis values? (as is shown in the images below)

My best guess so far is:

LineH = get(gca, 'Children');
x = get(LineH, 'XData');
y = get(LineH, 'YData');

offset=20;

nx = numel(x);
for i=1:nx
    x_shifted{i} = x{i} + offset;
end

set(LineH,'XData',x_shifted')

Which gives me the error:

Error using matlab.graphics.chart.primitive.Line/set
While setting the 'XData' property of Line:
Value must be a vector of numeric type

Thanks!

non_shifted_axis shifted_axis

like image 842
Peter Avatar asked Jan 27 '26 05:01

Peter


2 Answers

You have to encapsulate the 'XData' property name in a cell to update multiple plot objects at a time. From the set documentation:

set(H,NameArray,ValueArray) specifies multiple property values using the cell arrays NameArray and ValueArray. To set n property values on each of m graphics objects, specify ValueArray as an m-by-n cell array, where m = length(H) and n is equal to the number of property names contained in NameArray.

So to fix your error, you just have to change the last line to this:

set(LineH, {'XData'}, x_shifted');

And if you're interested, here's a solution that uses cellfun instead of a loop:

hLines = get(gca, 'Children');
xData = get(hLines, 'XData');
offset = 20;

set(hLines, {'XData'}, cellfun(@(c) {c+offset}, xData));
like image 192
gnovice Avatar answered Jan 29 '26 19:01

gnovice


Apparently you can't set the 'XData' property of all lines at the same time with a cell array.

EDIT It can be done; see @gnovice's answer.

What you can do is just move the set statement into the loop:

LineH = get(gca, 'Children');
x = get(LineH, 'XData');
y = get(LineH, 'YData');

offset=20;

nx = numel(x);
for i=1:nx
    x_shifted{i} = x{i} + offset;
    set(LineH(i),'XData',x_shifted{i}); % set statement with index i
end
like image 22
Luis Mendo Avatar answered Jan 29 '26 21:01

Luis Mendo