How to make a line plot and indicating data gap?
Ältere Kommentare anzeigen
Dear,
I have the following datafile (please see the attachement), the data consist of three columnes, Date (YYYY-MM-DD), Time (HH:MM) and the last column is the value which need to be ploted against time. But there is gap in the data for example there is no data between 2020-10-10 to 2020-11-02 and i dont want to connect the line, but instead, i would rather leave a shaded gap and mark it as no data. Do you have any suggestions?
I have tried this code but i had problem combining the data and time; am i on the right path?
data = readtable('data.csv');
dateColumn = data(:, 1);
timeColumn = data(:, 2);
valueColumn = data(:, 3);
% Convert date and time components to serial date numbers and here i get
% error
dateNumbers = datenum(dateColumn{:}, 'yyyy-mm-dd');
timeNumbers = datenum(timeColumn{:}, 'HH:MM');
dateTime = datetime(dateNumbers + timeNumbers, 'ConvertFrom', 'datenum');
plot(dateTime, valueColumn{:});
xlabel('Date and Time');
ylabel('Value');
title('Financial Data');
Example customization options:
grid on;
datetick('x', 'yyyy-mm-dd HH:MM', 'keeplimits');
legend('Value');
Akzeptierte Antwort
Weitere Antworten (1)
datestr is discouraged
I should mention that datestr is discouraged. Prefer datetime where possible.

For example,
dt = datetime("2020-10-01","Format","uuuu-MM-dd")
dt.Year, dt.Month, dt.Day
Consider xregion in MATLAB R2023a or later
% Read data as a timetable
tt = readtimetable("Data.txt", TextType="string", VariableNamingRule="preserve")
% Convert duration strings to duration objects
tt.("hr:min") = duration(tt.("hr:min"), InputFormat="hh:mm")
% Move duration data to timetable row-times
tt.date = tt.date + tt.("hr:min");
tt.date.Format = "uuuu-MM-dd HH:mm"; % Update datetime format to include hours and minutes
tt.("hr:min") = [] % Remove "hr:min" variable, which is no longer needed
% Plot timetable data and add an xregion with legend entry labeling it as
% having no data
plot(tt, "value");
xregion(datetime(2020,10,10), datetime(2020,11,02), DisplayName="No data");
xtickformat("uuuu-MM-dd HH:mm");
xtickangle(45);
legend(["value" "No data"]);
Kategorien
Mehr zu Dates and Time finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


