How to remove white space from beginning of a plot and adjust x-axis to start from 'January'?
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Anwesha Sharma
am 14 Feb. 2023
Kommentiert: Anwesha Sharma
am 18 Feb. 2023
I have a plot with monthly data over multiple years. But there is a white space in the beginning of the plot that I want to remove. If I use 'axis tight' or 'xlim([1 12])', then 'January' from the x-axis disappears (refer to image 'Temp_fig.jpg'). I want the x axis as 'Jan Feb Mar Apr Oct Nov Dec'.
T = table(datestr(Temp6ONDJFMAcorrect.DATE,'dd/mm/yyyy',),Temp6ONDJFMAcorrect.Temp);
[y,m,d] = datevec(T.Var1,'dd/mm/yyyy');
Tdate = table(y,m,d,'VariableName',{'year','month','day'});
TT = [Tdate,T(:,{'Var2'})];
TT.Properties.VariableName{4} = 'Temp';
yrs = TT.year;
yr = ismember(str2double(string(TT.year)),yrs);
x = reshape(TT.monthly(yr),7,[]);
y = reshape(TT.Temp(yr),7,[]);
plot(x,y)
xticklabels({'Jan', 'Feb','Mar','Apr','Oct','Nov','Dec'})
%% xlim([1,12]) %% this removes the white space but 'Jan' from x-ticks also disappears (see 'Temp_fig_1.jpg')
0 Kommentare
Akzeptierte Antwort
VBBV
am 14 Feb. 2023
xticks(1:7)
xticklabels({'Jan', 'Feb','Mar','Apr','Oct','Nov','Dec'})
You can try the above
Weitere Antworten (1)
Cris LaPierre
am 17 Feb. 2023
Bearbeitet: Cris LaPierre
am 17 Feb. 2023
Perhaps a bit more difficult to understand at first, but here's another way to do it using findgroups and splitapply.
file = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/1295380/Temp_6_ONDJFMA_correct.csv';
opts = detectImportOptions(file);
opts = setvaropts(opts, "DATE","InputFormat","dd/MM/yyyy");
T = readtable(file,opts);
% Need to create x values that are shared across all years so they overlap
% Here, I create a copy of DATE and change the year so all are 1960
T.plotDATE = T.DATE;
T.plotDATE.Year = year(T.DATE(1))
% Find groups
G = findgroups(year(T.DATE));
% Plot. Need 'figure' since 'hold on' is used before first plot command
figure
hold on
splitapply(@(x,y)plot(x,y),T(:,["plotDATE","Temp"]),G)
hold off
% A datetime axis will include the year. This removes that by manually
% labeling X Ticks
ax = gca;
xlbls = ax.XTickLabel;
ax.XTickLabel = xlbls;
Since you have to manually label the XTicks anyway, another way to do this is create a Month column with the month names as categoricals. The categorical function lets you specify an ordered set. The plot is a little bit different (space between Y axis and Jan)
T2 = readtable(file,opts);
T2.Month = categorical(month(T2.DATE,"monthofyear"),...
1:12,{'Jan','Feb','Mar','Arp','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'})
G = findgroups(year(T2.DATE));
figure
hold on
splitapply(@(x,y)plot(x,y),T2(:,["Month","Temp"]),G)
hold off
Siehe auch
Kategorien
Mehr zu Dates and Time finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!