Datetick does not set x-ticks accurately
2 views (last 30 days)
Show older comments
Hello Community, I got a problem using datetick in my figure. Here is what I want:
-time printed on my x-axis as "lap time" using the format "MM:SS" with speed on y-axis
Here is my code so far:
tsec=time_s(1:5266,1);
v_soll=v_target_kmph(1:5266,1);
axes1 = axes;
hold(axes1,'on');
plot(tsec,v_soll,'DisplayName','Speed','LineWidth',2);
xlabel('Time [mm:ss]','FontSize',14,'Interpreter','latex');
dateFormat = 15; % or dateFormat = 'MM:SS';
datetick('x',dateFormat, 'keeplimits', 'keepticks')
ylabel({'Speed [kmh]'},'FontSize',14,'Interpreter','latex');
xlim(axes1,[0 530.893315881894]);
ylim(axes1,[0 300]);
box(axes1,'on');
set(axes1,'FontName','SansSerif');
tsec looks like this:
0
0.100000000000000
0.200000000000000
0.300000000000000
0.400000000000000
0.500000000000000
0.600000000000000
0.700000000000000
0.800000000000000
0.900000000000000
1
1.10000000000000
1.20000000000000
1.30000000000000
1.40000000000000
1.50000000000000
1.60000000000000
1.70000000000000
1.80000000000000
1.90000000000000
2
2.10000000000000
...... (until)
526.500000000000
Using datestr(tsec/24/3600, 'MM:SS'); makes it correctly displayed as I want it but I cant use that in the plot (i.E. 08:46)
Using the Code above gives me the following result attached in file
0 Comments
Accepted Answer
Walter Roberson
on 23 Mar 2018
datetick works with datenum which are defined as being in terms of full days and fractions of a day. Your times are therefore incrementing by 1/10 of a day, so 2.4 hours.
With a 526 range, the default ticks are going to be nice round integers, probably the hundreds, perhaps the 50s as well. You keepticks so MATLAB will not attempt to recompute ticks that align with nice round times. And the thing is, integer datenum always correspond to midnight, so you are always going to get 00:00
Divide your seconds by the number of seconds per day, and do not keepticks
Or if you have a release since R2014b then switch to duration() objects by plotting seconds(tsec) on the x axis and do not use datetick
More Answers (0)
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!