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

56 visualizaciones (últimos 30 días)
Alishan Amirali
Alishan Amirali el 25 de En. de 2022
Editada: DGM el 25 de En. de 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?

Respuestas (1)

DGM
DGM el 25 de En. de 2022
Editada: DGM el 25 de En. de 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 comentarios
Alishan Amirali
Alishan Amirali el 25 de En. de 2022
Editada: Alishan Amirali el 25 de En. de 2022
Thanks! This helped quite a bit; however, for some reason the dates are combining into one long string. For example,
omissions_per_day =
2×5 cell array
{'01-10-22'} {'01-11-22'} {'01-12-22'} {'01-13-22'} {'01-14-22'}
{[ 5]} {[ 9]} {[ 16]} {[ 2]} {[ 293]}
This is the cell array I am working with. However when I enter
[omissions_per_day{1,:}]
I get
'01-10-2201-11-2201-12-2201-13-2201-14-22'
Am I entering something incorrectly?
DGM
DGM el 25 de En. de 2022
Editada: DGM el 25 de En. de 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)

Iniciar sesión para comentar.

Categorías

Más información sobre Line Plots en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by