How can I turn the elements of a cell array into a bar graph?
56 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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?
0 comentarios
Respuestas (1)
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]
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
el 25 de En. de 2022
Editada: Alishan Amirali
el 25 de En. de 2022
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]
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)
Ver también
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!