Lettering a Bar Chart

조회 수: 1 (최근 30일)
ALEXANDER MOUNTAIN
ALEXANDER MOUNTAIN 2021년 3월 17일
편집: the cyclist 2021년 3월 18일
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

채택된 답변

the cyclist
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')')

추가 답변 (1개)

Adam Danz
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
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 CenterFile Exchange에서 Printing and Saving에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by