Set tick label of the color bar with dates in the format yyyy-MM-dd HH:mm:ss.
39 views (last 30 days)
Show older comments
Chiara Lanzi
on 11 Dec 2024 at 14:18
Commented: Chiara Lanzi
on 12 Dec 2024 at 9:10
Dear all,
I have a dataset (x,y,z) that I am plotting over time. The time column was originally in the following format 'yyyy-mm-dd HH:mm:ss'.
For the plot, I converted it to decimal year, and this is the label that appear in the colorbar. But I would like to have the colorbar label in the format 'yyyy-mm-dd HH:mm:ss'.
I tried something similar to this:
hcb.TickLabels = datestr(dates, 'yyyy-MM-dd HH:mm:ss');
but the label are not the corrected one (see figure).
Has someone a suggestions?
Thanks to all the will reply,
Chiara
4 Comments
Steven Lord
on 11 Dec 2024 at 16:15
You used "mm" twice in the format, and that is interpreted as the minutes data. If you were using datetime MATLAB should have warned you about this as shown below. You want to use MM or MMM for months.
dt = datetime('now')
F = dt.Format
dt.Format = replace(F, 'MMM', 'MM') % 2-digit month instead of short name
dt.Format = replace(F, 'MMM', 'mm') % minutes in place of months
Accepted Answer
Cris LaPierre
on 11 Dec 2024 at 15:56
I'm not sure how you created the dates variable used to set the tick labels. It can be difficult to convert decimal years back into a date string since you often lose the precision needed to accurately reconstruct the datetime.
Here's an example of how you could avoid that by manually creating the colorbar ticks and labels.
Z = peaks;
times = datetime('now','Format','yyyy-MM-dd HH:mm:ss') + days(Z);
dyears = decyear(times)
surf(dyears)
hcb = colorbar;
% manually set the colorbar tick locations and labels
start = min(times(:));
stop = max(times(:));
dticks = linspace(start,stop,10);
hcb.Ticks = decyear(dticks);
hcb.TickLabels = string(dticks);
ax = gca;
ax.OuterPosition(3) = 0.8;
More Answers (0)
See Also
Categories
Find more on Axis Labels in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!