histogram returns an error for vector data

3 views (last 30 days)
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.

Answers (1)

Steven Lord
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
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)
counts = 1×6
1 1 1 1 1 1
edges = 1×7
-0.5000 0.5000 1.5000 2.5000 3.5000 4.5000 5.5000
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)
counts = 1×6
1 1 1 1 1 1
edges = 1×7 datetime array
12-Jul-2022 21:00:00 13-Jul-2022 18:00:00 14-Jul-2022 15:00:00 15-Jul-2022 12:00:00 16-Jul-2022 09:00:00 17-Jul-2022 06:00:00 18-Jul-2022 03:00:00
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

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!