Repeating time values on x-axis
1 次查看(过去 30 天)
显示 更早的评论
Noush
2021-11-23
Hi there,
I have a table that contains a first column with time of the day and a second with the power of a machine. I would like to plot the power on the y-axis and the time on the x-axis for a week.
When I use the command plot(time,power) I get this: ![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/810524/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/810524/image.png)
The graphs overlap, as the times repeats itself for each day. I don't want that. I dont want to use the xtick method to solve this, as it would require me to specify each xticklabel right? That would take too long. Rather, I'd like the graph to produce the xticks automatically and plot in such a way that the graphs for each day are lined up after each other.
I also have a column with the dates, I just don't know how to put that all together in the correct way for it to plot it the way I want.
Can you help?
Thank you!
14 个评论
Noush
2021-11-23
Thank you that parshly worked. I couldnt add them using datetime somehow, so I have added as you can see below, but the xticks only include the dates now. How can I change it so it adds the times as well?
dt = P2T.date + timeofday(P2T.time)
WeekdayGraph = plot(dt,power,"r-*","LineWidth",2)
Peter Perkins
2021-11-23
I'm confused.
The figure in the original post appears to be a numeric against a datetime--look at the labels and the secondary label for the horizontal axis. Unless Noush has done something by hand, that's a datetime plot. So then I am led to think that the data already include a datetime, and all the times are on the same day.
And then this
dt = P2T.date + timeofday(P2T.time)
looks like extracting time of day from a datetime only to add that to pure dates to get a datetime again.
Noush, you need to show what you have in your time variable. I'm guessing you've created something other than what you think it is.
Noush
2021-11-24
No, each plot corresponds to a different day. Thats the whole issue, the plots should be appearing after each other and not on top of each other. As you can see below, this is the table I am working with (in the code I included here I translated from germand, date = Datum in Germand and time =Zeit, power = Leistung).
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/811714/image.png)
What I get with the new code I commented is this: ![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/811719/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/811719/image.png)
Which is what I want (although you are right, I don't really understand what I wrote there and why it works). This is almost what I want, I just need the x-axis to display the times as well and not just the date.
Can you tell me how to fix this? Thank you!
Peter Perkins
2021-11-24
I don't know what you wrote either, you have not provided any code or data.
If you are asking what went wrong in the original plot, I can only refer you back to my previous response, which is almost certainly the case. If you are asking how to get times in the tick labels, take a look at the axes properties:
>> d = datetime(2021,11,24) + minutes(0:30:14400);
>> x = 1:length(d);
>> plot(d,x)
>> ax = get(gca,"XAxis")
ax =
DatetimeRuler with properties:
Limits: [Nov 24, 2021 Dec 04, 2021]
TickValues: [Nov 24, 2021 Nov 25, 2021 Nov 26, 2021 Nov 27, 2021 Nov 28, 2021 Nov 29, 2021 Nov 30, 2021 Dec 01, 2021 … ]
TickLabelFormat: 'MMM dd'
Show all properties
Noush
2021-11-30
Hi again,
sorry for not providing the code immediately, here it is.
As you can see, "Datum" and "Zeit" (being date and time) are already datetime arrays. However, I need the x-axis to consider both the date and the time, and I don't know how to do that.
When using the code below, with the command dt = P2T.date + timeofday(P2T.time)
somehow that parshly works, although I don't full understand why. And as I said, still on the graph the time values don't show up, which I need. Can you help me out?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/818309/image.png)
dpb
2021-11-30
编辑:dpb
2021-11-30
The problem in your original table and what Peter was explaining is that you convert Zeit into a datetime instead of a duration variable. A datetime ALWAYS includes a date even if the format to display it hides it as you do with your input conversion.
To illustrate--
>> zeit=datetime('0030','InputFormat','HHmm','Format','h:mm a')
zeit =
datetime
12:30 AM
>> datestr(zeit)
ans =
'30-Nov-2021 00:30:00'
>>
shows that even though the display value on the screen looks like just a time of day, it really is a full-fledged date AND time inside. All operations on the variable zeit other than the output of the representation on the screen use the full internally stored value of the variable; the display format is simply that--just what you see, not what the value actually is. It's no different than showing only the integer portion of a floating point variable by using an integer format expression with a double precision variable...
>> p=pi; fprintf('%.0f\n',p)
3
>>
Above you recognize the the variable p still == pi internally, you've just not displayed the fractional portion. That's what you've done with the time variable -- just hidden the implicit day value that goes along with the variable by specifying a format string to use to display the result.
The difference between numeric and time-related variables is that you have to make the format explicit when you display numeric values other than the default setting whereas time variables carry a format along with them inherent in the time variable object. This can, agreed, be confusing.
Secondly, by using a datetime object for zeit, you made it such that you can't add the "time"(*) to the date because math operations other than ordinal comparison aren't defined...you can't add two datetimes. As Peter showed more directly and as you did above, you CAN (and must) add a duration to a datetime to get a datetime with both a date and time.
(*) And, of course, it wouldn't make any sense to add the datetime value of the zeit variable to the date, anyway, which is why the operation is undefined.
You can get to your same location as above with
dt=datetime(T(C:B,1),'InputFormat','yyyyMMdd')+duration(T(C:B,2),'InputFormat','HHmm');
using the input data themselves without the intermediaries.
Or, in all likelihood if the data come from an input file originally, then you could use the import options object with readtable and read them in as datetime and duration arrays directly.
To set the plot tick format, use Peter's hints above
hXAx=get(gca,"XAxis"); % return the handle to the x-axis
which will be a datetimeruler object. You can set the format string for it to anything allowable for a datetime -- the problem you'll likely run into is that there's limited room on the axis for date strings so when you try to add both dates and time they'll probably get too crowded to read. Also you only get tick labels where there are ticks and the default appears to have placed just one tick per day. Again, you can change that by setting the XTicks property to a series of datetime values of your choosing, but you're going to run out of room real fast for display.
Noush
2021-11-30
Thank you very much for answering my question so elaborately, it makes it very clear what was going on.
With your line of code, the input format is causing some trouble. HHmm is not supported for the duration functionan, but hh:mm, which is supported, is not how my data in my table is stored.
Is there a way to use "duration" anyways?
dpb
2021-11-30
编辑:dpb
2021-11-30
Oh,yes. I just had a discussion w/ TMW on the limitations in the duration object regarding input formats this past week and forgot already again it has overly restrictive string formatting input requirements.
You can try something like
duration(datestr(datetime(T(C:B,2),'InputFormat','HHmm','Format','h:mm a'),'HH:MM'),'InputFormat','hh:mm')
and see if it will work for you. That's going through the datetime object and using datestr to reformat the string into a recognizable form. In theory, it should work, but we all are aware of the difference between theory and... :)
If it doesn't succeed, the simplest workaround will be to introduce a temporary variable in between to extract the [h,m] vectors from the datetime and then pass that to duration
zeit=datetime(T(C:B,2),'InputFormat','HHmm','Format','h:mm a'); % go ahead with datetime first
[h,m]=hms(zeit); % get hr, min from it
dt=datetime(T(C:B,1),'InputFormat','yyyyMMdd')+duration(h,m,0); % create full datetime
If you would attach a section of the actual data file, folks could play with the real thing...
dpb
2021-11-30
NB: the formatting strings for datestr do NOT match up with those of the datetime and duration objects. This is a wart left over from the era of datenum before the new time objects were introduced.
dpb
2021-11-30
Alternative to the above reading with datetime, one coud do substring selection and conversion -- but if the string isn't always four characters as the single 'h' in the format string 'h:mm' implies, then that's fraught with an additional complication of either first augmenting short strings or only picking extant characters since addressing first two characters for a three-character string won't be correct.
Alternatively, there's the convert to double and then use mod() operations to split off the two pieces...
None of these are hard, but all add quite a bit more code to get right...
Peter Perkins
2021-11-30
dpb is correct, the supported formats for converting from text to duration are currently limited. At one point, there was no support, and the recommended approach was to convert text to datetime (datetime supports almost unlimited input formats), and then immediately call timeof day on that.
This is still a good way to convert text whose format duration doesn't yet support.
dpb
2021-11-30
The other markedly different alternative would be to catenate the two variables as text and then scan them as a composite datetime...
dt=datetime(strcat(T(C:B,1),T(C:B,2)),'InputFormat','yyyyMMddhhmm');
which may well be the shortest, best way in the end.
NB: the above input format string will require the times all have double-digit hours, not single. The one-letter form of 'h' format string only works if the hour and minute fields are separated with the colon or other punctuation; it's simply too ambiguous a format without that indicator.
dpb
2021-11-30
"... convert text to datetime ... then immediately call timeof day on that."
Ah! I don't recall having come across that suggestion before, Peter, but it's a good one. I didn't even think of timeofday ...
回答(0 个)
另请参阅
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)
亚太
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)