plot Datetime on x Axes
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
0 개 추천
Hello! I have a endless while loop, that generates every 20 min a number. I'm trying to figure out how to plot the data with the dates on the x axis and numbers on the Y.
how can i plot the date and time on x axes?
I'm pretty new to Matlab, would really appreciate any help!
채택된 답변
Benjamin Großmann
2020년 3월 9일
0 개 추천
There are mainly 2 possibilities
- You can use datetick() to format your x axis ticks to date or time values
- You can define your x-values as datetime() and the plot command automatically formats your x-axis with dateticks
For a mwe, we can assume that we start "now" and are collecting data for 12 hours resutling in a time vector t
t = datetime('now'):minutes(20):datetime('now')+hours(12);
y = rand(size(t));
plot(t, y)
You can also append t with the current time
t = []; % initialization
% ...
% ...
% ...
% every iteration / callback
t(end+1) = datetime('now');
As you are new to matlab, i would also recommend not to use a "endless while loop, that generates every 20 min a number". Have a look at the timer class. With the timer class you can define an instance of the timer which calls a function (schedules) every 20 minutes "in the background". Please let me know if you need help with that.
댓글 수: 5
MoHa
2020년 3월 9일
Thanks you for your answer Benni,
t = datetime('now'):minutes(20):datetime('now')+hours(12);
this is for only next 12 hours. actually i work on a permanent Monitoring and i get the data eyery for Example 30 min (adjustable in my GUI). in every period my code calculates a number at specific time. i want to plot the numbers with the his time on x axes. therefore i have to have a unlimited time (not limited of 12 hours). i attached my func. please tell how can i optimise my code (ex. timer).
other question is abaout: tic - toc
i dont know why gives me this a wrong diuration. this code takes for ex. 4 minutes time, but tic toc displays some seconds ??
if ~isempty(instrfind)
fclose(instrfind);
delete(instrfind);
end
% global S;
global ComPort; global baudrate;global ScanFullName; %global newFileName;
global newFileNameExtra; global StP;
S=serial(num2str(ComPort),'Baudrate',str2num(baudrate));
fopen(S);
t1=datestr(now);
disp(t1)
% code ...
hi=1.453;
% i get the time from my gui
Repeat=str2double(get(handles.MonitoringTime,'String'));
Repeat=Repeat*60;
plt=animatedline('color','r');
hold on
grid on
xlabel('Time [Minutes]','color','w');
ylabel( '3d-Displacement [Meter]','color','w')
title('Station stability');
set(gca,'xcolor','w','ycolor','w')
while true
tic
% 1 Cal & Set PPM
%func ...
% set the ppm
% code ....
% 2 Ref. Points Measurement
% func ...
% 3 Prepare the Meseurements and Reference File to Helmert Transformation
% func ...
% 4 Calc. Station Coord. with Helmert Transformation & Set Coord.
if ~isempty(instrfind)
fclose(instrfind);
delete(instrfind);
end
S=serial(num2str(ComPort),'BaudRate',str2num(baudrate));
fopen(S);
fst=fopen(newFileNameExtra,'a');
[xyz,tp,ac,tr]= freeStation_with_HelmertTr;
St3d_Dist=sqrt(((StP(1)-xyz(1))^2)+((StP(2)-xyz(2))^2)+((StP(3)-xyz(3))^2));
assignin('base','St3d_Dist',St3d_Dist);
% plotting the data (y) and time (x)
t = datevec(now);
q=t(1,5);
addpoints(plt,q,St3d_Dist);
view(handles.StAndRefDisplacement)
drawnow
% set the calculated coord. with Hel. Transformation
% code...
% Writting data into a file
fprintf(fst,'StationCoordinate:\n');
fprintf(fst,'\t %d %d %d\n', xyz);
fprintf(fst, 'Translation for measured Points resultet from Helmert Transformation\n');
fprintf(fst, '\t %d \t %d \t %d \t \n', tr);
fprintf(fst,'ThreeD_Difference_to_first_StationCoordinate:\n');
fprintf(fst, '\t %d \n', St3d_Dist);
fprintf(fst, 'Transformation Parameter of measured Points resultet from Helmert Transformation\n');
fprintf(fst, '\t %d \n', tp);
fprintf(fst, 'Accuracy of Helmert Transformation of measured Points\n');
fprintf(fst, '\t %d \n', ac);
fclose('all');
movefile(newFileNameExtra, 'output_clouds')
% 5 Start Scanning
scannerEditedMe_successfullyDone
fprintf('Scanning Successfully done!\n')
t2=datestr(now)
disp([t1;t2])
T=toc
pause(Repeat-T)
end
thanks for your help
Let's use a simple example as introduction:
clearvars
close all
clc
delete(timerfindall);
t = timer; % timer instance
t.ExecutionMode = 'fixedRate'; % can be 'singleShot', 'fixedRate', 'fixedDelay', 'fixedSpacing'
t.Period = 0.1; % Period in seconds
t.StartFcn = @myTimerInit; % function which is evaluated at start of timer --> initialization
t.TimerFcn = @myTimerFunction; % function which is evaluated every period
t.start % start the timer#+
% use t.stop to stop the timer, timerfindall to find all timers and delete(timerfindall) to delete all timers
The StartFcn
function myTimerInit(src, evnt)
% some initial values, could also be datetime.empty, but then plotting
% makes some problems
src.UserData.t = datetime('now');
src.UserData.y = 0;
src.UserData.fig = figure('CloseRequestFcn', {@myCloseRequestFcn, src});
src.UserData.ax = axes('Parent', src.UserData.fig);
src.UserData.p = plot(src.UserData.ax, src.UserData.t, src.UserData.y);
end
The TimerFcn
function myTimerFunction(src, evnt)
src.UserData.t(end+1) = datetime('now'); % you can also do some windowing etc. to limit the length of the vector
src.UserData.y(end+1) = rand;
src.UserData.p.XData = src.UserData.t;
src.UserData.p.YData = src.UserData.y;
end
The close request of the figure to stop the timer before closing the figure
function myCloseRequestFcn(src, evnt, mytimer)
if isvalid(mytimer)
mytimer.stop;
mytimer.delete;
end
closereq
thanky again for your Answer,
sorry i didnt get how can i use them in my code. where can i set the Time interval?
beacuse i define it (Time interval) in my gui (pls. see Pic).
and how can i set parameter (St3d_Dist) for y axes which i get in every iteration?
really appreciate for your solution!
Benjamin Großmann
2020년 3월 9일
You can set the timer interval via the period property of the timer class. See line 9 in my first code snippet.
First, write a function and put everything inside the function which should be evaluated with the specified rate. This is going to be your timerFcn. Please note that a timer fcn (and other callbacks) must have an input argument for the source and event. You can add additional arguments and pass values to those callbacks like i did with the myCloseRequestFcn().
If you want to store data, you can use the UserData of the timer class as I did with the x data, y data and so on.
Then you just have to adapt the definition of the timer instance from my first code snippet.
If you can post a mwe of your problem, than I can try my best to support you with the timer function.
The "animatedline" now supports datetimes and durations for all axes as of R2023a!
So, you no longer need to convert your datetimes into a "datevec" which should give your plots a nicer looks with better axes ticks. In order to plot your data on an "animatedline" you can now utilize the following example:
h = animatedline(NaT, NaN);
addpoints(h, Xdata, Ydata);
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Graphics Performance에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
