Plotting an array of dates on the x-axis
1 次查看(过去 30 天)
显示 更早的评论
I am am writting a program where I read data from a txt file that has dates that correspond to different data sets. This program has to be reusable for other txt files so for getting my plot with dates on the x-axis I create a cell that fills with all the dates it reads caled dates.
'31-May-2019 11:37:29'
'31-May-2019 11:45:25'
'22-Jul-2019 18:05:55'
'22-Jul-2019 18:06:31'
'24-Jul-2019 18:00:07'
'24-Jul-2019 18:00:30'
For example this. How do I get these dates on the x-axis from the cell containing them.
Thanks
0 个评论
回答(1 个)
Steven Lord
2020-7-21
Use datetime.
x = {'31-May-2019 11:37:29'
'31-May-2019 11:45:25'
'22-Jul-2019 18:05:55'
'22-Jul-2019 18:06:31'
'24-Jul-2019 18:00:07'
'24-Jul-2019 18:00:30'}
dt = datetime(x)
plot(dt, (1:6).^2)
3 个评论
Steven Lord
2020-7-21
When I ran the code I posted, the X axes ticks included the date information from the datetime array x.
Do you want 108 ticks, each with the full date and time information? That seems like the plot will be quite crowded. It is possible to do, but I'm not certain that's what you really want.
% Make sample data
x = datetime('now')+minutes(0:107);
% Plot the sample data
h = plot(x, 1:108);
% Set the ticks -- notice they overlap quite a bit
xticks(x);
% Let's rotate the ticks. We need the handle to the axes to do this.
ax = ancestor(h, 'axes');
ax.XTickLabelRotation = 90;
% Note that this plots the times but not the date in each label
% (except maybe if you're running this close enough to midnight.)
% If you want the date in each and every label:
xticklabels(string(x))
If this isn't what you're trying to do, can you provide a bit more information about how you're trying to make the axes appear? If you have a picture that shows what you want, a link to that would be useful.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!