# How can I turn the elements of a cell array into a bar graph?

9 views (last 30 days)
Alishan Amirali on 25 Jan 2022
Edited: DGM on 25 Jan 2022
I have a 2x5 cell array of dates in one row and number of trials in the second row. I wanted to plot this on a bar graph with the dates being the x axis and the trials being the y axis. How could I write this in matlab?

DGM on 25 Jan 2022
Edited: DGM on 25 Jan 2022
Here's a start.
This will space all the bars evenly, regardless of the date spacing:
% create example array
t = num2cell(datetime(2017,[1 2 4 5 7],1));
n = num2cell(randi(100,1,5));
C = [t;n]
C = 2×5 cell array
{[01-Jan-2017]} {[01-Feb-2017]} {[01-Apr-2017]} {[01-May-2017]} {[01-Jul-2017]} {[ 55]} {[ 42]} {[ 11]} {[ 77]} {[ 26]}
bar(1:size(C,2),[C{2,:}])
xticklabels(datestr([C{1,:}]))
set(gca,'XTickLabelRotation',30) This will position the bars relative to the dates:
bar([C{1,:}],[C{2,:}])
set(gca,'XTickLabelRotation',30) ##### 2 CommentsShowHide 1 older comment
DGM on 25 Jan 2022
I assumed those were datetimes. These are the same examples, but using your array:
t = {'01-10-22' '01-11-22' '01-12-22' '01-13-22' '01-14-22'};
n = {5 9 16 2 293};
C = [t;n]
C = 2×5 cell array
{'01-10-22'} {'01-11-22'} {'01-12-22'} {'01-13-22'} {'01-14-22'} {[ 5]} {[ 9]} {[ 16]} {[ 2]} {[ 293]}
t = datetime(C(1,:),'inputformat','MM-dd-yy'); % convert to datetime
bar(1:size(C,2),[C{2,:}])
xticklabels(datestr(t))
set(gca,'XTickLabelRotation',30) t = datetime(C(1,:),'inputformat','MM-dd-yy'); % convert to datetime
bar(t,[C{2,:}])
set(gca,'XTickLabelRotation',30) Since the elements are uniformly spaced, the two examples are essentially the same. The tick label formatting with the second case can be adjusted using datetick() if desired.
If you don't even want to deal with datetimes, the first example can be done just using the cell array of chars as labels:
bar(1:size(C,2),[C{2,:}])
xticklabels(C(1,:))
set(gca,'XTickLabelRotation',30) 