Lettering a Bar Chart
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
the cyclist
2021-3-17
编辑:the cyclist
2021-3-17
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 个评论
更多回答(1 个)
Adam Danz
2021-3-17
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 个评论
the cyclist
2021-3-18
编辑:the cyclist
2021-3-18
@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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Printing and Saving 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!