Lettering a Bar Chart
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
ALEXANDER MOUNTAIN
le 17 Mar 2021
Modifié(e) : the cyclist
le 18 Mar 2021
I want to create a bar chart and label my XAxis in letters for as many bars as there are. For example if I have 4 bars I want them to be individually labeled A, B, C, D and I want it to work for any amount of bars. I know using sprintf with %d will do what I want with numbers and I thought that using %s or %c would do what I wanted with letters, but it's just returning empty character boxes. What do I have to change to print letters instead?
yData = [10, 25,15,10,25,20]
myFig = gcf;
myAx = axes(myFig);
myPlot = bar(myAx, yData);
myAx.Title.String = 'Data Visualization';
myAx.YLabel.String = 'Value';
myAx.XLabel.String = 'Category';
myAx.YLim = [0 30];
endAt = length(myAx.XAxis.TickLabels);
for i = 1:endAt
myAx.XAxis.TickLabels{i} = sprintf ('%d' , i)
end
0 commentaires
Réponse acceptée
the cyclist
le 17 Mar 2021
Modifié(e) : the cyclist
le 17 Mar 2021
Here is one way, closely based on yours:
yData = [10, 25,15,10,25,20];
myFig = gcf;
myAx = axes(myFig);
myPlot = bar(myAx, yData);
myAx.Title.String = 'Data Visualization';
myAx.YLabel.String = 'Value';
myAx.XLabel.String = 'Category';
myAx.YLim = [0 30];
endAt = length(myAx.XAxis.TickLabels);
for i = 1:endAt
myAx.XAxis.TickLabels{i} = sprintf ('%s' , char(i-1+'A'));
end
Note my changes inside sprintf.
But you don't need a for loop for the labeling:
set(gca,'XTickLabel',char((0:endAt-1) + 'A')')
0 commentaires
Plus de réponses (1)
Adam Danz
le 17 Mar 2021
It's better to avoid setting tick labels when possible.
Instead, use a categorical variable (xCats) for x, defined by letters starting with A to however many values are in yData.
yData = [10, 25,15,10,25,20];
xCats = categorical(num2cell(char((0:numel(yData)-1)+'A')));
myFig = gcf;
myAx = axes(myFig);
myPlot = bar(myAx, xCats, yData);
1 commentaire
the cyclist
le 18 Mar 2021
Modifié(e) : the cyclist
le 18 Mar 2021
@Adam Danz makes a great philosophical programming point. Since 'A', 'B' , etc are presumably referencing the data themselves, it is better to reflect that in the data, not just the labels.
It's a little bit of a lazy quirk of MATLAB (and other languages) that it allows the programmer to make a bar chart by specifying only the y-data -- and then adds the probably-wrong numeric x-labels automatically.
It's a shame that the creation of the vector {'A','B', ..., arbitrary length} is a bit awkward, because this is truly the better way to go.
Voir également
Catégories
En savoir plus sur Bar Plots dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

