How to remove white space from beginning of a plot and adjust x-axis to start from 'January'?
47 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
更多回答(1 个)
Cris LaPierre
2023-2-17
编辑:Cris LaPierre
2023-2-17
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Line Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!