histogram returns an error for vector data
1 次查看(过去 30 天)
显示 更早的评论
When I try to call the histogram function I get an error.
Here's an example using a simple vector
xtest = [1 2 3 4 5]
histogram(xtest)
Here is the error message:
Error using histogram (line 172)
Values plotted against x-axis must be datetime values. To create datetime values, use the
DATETIME function.
0 个评论
回答(1 个)
Steven Lord
2020-8-7
You can't create a histogram from double data in an axes in which you've already plotted datetime X data.
v = 0:5;
t = datetime('today')+days(v);
plot(t, v.^2)
hold on
histogram(v) % will error
Create your histogram in another axes, one that you haven't plotted into yet or one in which you've plotted using double X data.
2 个评论
Steven Lord
2022-7-13
Let's say you have an axes in which you've plotted date and time-based data.
v = 0:5;
t = datetime('today')+days(v);
plot(t, v.^2)
hold on
If I were to call histogram to add that plot to this axes, it would select bins centered around 0, 1, 2, 3, 4, and 5.
[counts, edges] = histcounts(v)
Where exactly should the bin edges [-0.5, 0.5] be plotted on this date and time axes? You could argue that the value 0 should map to midnight today (00:00 on July 13th, 2022). But should 0.5 be marked as half a day after that (12:00 on July 13th, 2022), half an hour after (00:30 on July 13th, 2022), half a year after (00:00 on January 13, 2023), or half of some other time unit?
Rather than try to guess, MATLAB will error and require you to create your histogram from datetime data.
figure
v = 0:5;
t = datetime('today')+days(v);
plot(t, v.^2)
hold on
[counts, edges] = histcounts(t, 6)
Now the bin edges are datetime values, and that MATLAB can easily plot since the X axis is already in units of dates and times.
histogram(t, 6) % Using the datetime data not the double data with 6 bins
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Distribution Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!