histogram returns an error for vector data
1 view (last 30 days)
Show older comments
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 Comments
Answers (1)
Steven Lord
on 7 Aug 2020
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 Comments
Steven Lord
on 13 Jul 2022
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
See Also
Categories
Find more on Data Distribution Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!