Set the startdate and enddate of x axis using plot
Afficher commentaires plus anciens

This is the plot i have done. I would like to set the 0 value of x axis to 2019 12 26 and 71 value of x axis to 2019 12 30. The values within is not needed. There is 71 data points for y axis.
Réponses (2)
Walter Roberson
le 12 Avr 2020
0 votes
linspace works with datetime objects. datetime(year, month, day)
Ameer Hamza
le 13 Avr 2020
By default, MATLAB creates a numeric ruler for XAxis. There is no direct way to convert numeric ruler to a datetime ruler. The only way is to create a new figure, format the axis, and copy the axis to the first axes object. The following shows an example by creating a temporary invisible figure.
Create an example figure with numeric ruler at x-axis
f1 = figure();
ax1 = axes();
t = 5:0.1:30;
p1 = plot(t, sin(t));

Create an invisible figure with datetime ruler
%% now create an invisible axes with datetime ruler as X-Axis
dates = datetime('2019 12 26', 'InputFormat', 'yyyy MM dd'):datetime('2019 12 30', 'InputFormat', 'yyyy MM dd');
f2 = figure('Visible', 'off');
ax2 = axes();
plot(dates,0);
ax2.XAxis.TickValues = dates;
Copy the ruler from invisible figure to the original figure
%% adjust the axis limits of 1st axes and assign the ruler from second axes to first
p1.XData = (p1.XData - p1.XData(1))/(p1.XData(end) - p1.XData(1))*(numel(dates)-1);
ax1.XAxis = ax2.XAxis;
%% delete the invisible figure
delete(f2);

2 commentaires
Walter Roberson
le 13 Avr 2020
This can be done as shown, but it is much easier to just to plot with datetime objects in the first place.
You do not need to construct a new figure to get to a DatetimeRuler:
dt_ruler = matlab.graphics.axis.decorator.DatetimeRuler;
Now here set dt_ruler Limits, TickValues, TickLabelFormat. Then
p1.XRuler = dt_ruler;
Ameer Hamza
le 13 Avr 2020
Thanks. The code is simpler by directly assigning the datetime ruler. For OP's reference, here is the code using method suggested by Walter
f1 = figure();
ax1 = axes();
t = 5:0.1:30;
p1 = plot(t, sin(t));
%%
ax1.XRuler = matlab.graphics.axis.decorator.DatetimeRuler;
drawnow;
dates = linspace(datetime('2019 12 26', 'InputFormat', 'yyyy MM dd'), datetime('2019 12 30', 'InputFormat', 'yyyy MM dd'), numel(t));
p1.XData = dates;
dates2 = datetime('2019 12 26', 'InputFormat', 'yyyy MM dd'):datetime('2019 12 30', 'InputFormat', 'yyyy MM dd');
ax1.XAxis.TickValues = dates2;
Catégories
En savoir plus sur Axes Appearance dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!