![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/196555/image.png)
Plot bar chart from elements of string
조회 수: 6 (최근 30일)
이전 댓글 표시
I want to create a bar graph showing the number eruptions for the respective countries. However, the data provided is in a string and I need to loop through the data set to count the respective countries. As it is in a string format, I am struggling to extract out the number of counts for each country in a loop. I managed to use strcmp and find, but the plot does not work. How do I create a loop which plots the chart sucessfully?
% Finding each individual country "eachcountry"
eachcountry = unique(thecountry);
% Counting the length of year for j
% loop through each index
for j = 1:length(thecountry)
A = strcmp('%s'eachcountry(j),thecountry);
% Obtaining index of respective country
indexcountry = find(A)
numberofcounts = numel(indexcountry);
% Plotting with rectangle function, start from the first year, for x axis,
% start from 0 for y axis. Width is 1, while frequency is number of
% counts.
rectangle('Position',[eachcountry(j) 0 1 numberofcounts])
hold on
end
% Labelling axes
xlabel('Country')
ylabel('Frequency')
댓글 수: 0
채택된 답변
Stephen23
2018년 9월 26일
편집: Stephen23
2018년 9월 26일
>> [U,~,X] = unique(thecountry);
>> cnt = histc(X,1:numel(U));
>> bar(cnt)
creates this:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/196555/image.png)
You might want to read this too:
댓글 수: 2
Stephen23
2018년 9월 26일
편집: Stephen23
2018년 9월 26일
@Madlab: see my edited answer, which plots the number of eruptions for each country. No loops are required. You can easily add country labels too:
>> set(gca,'XTick',[])
>> cellfun(@(x,s)text(x,-1,s,'Rotation',270),num2cell(1:numel(U)),U.')
Giving:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/198038/image.png)
With newer MATLAB versions you can simply add the names as XTickLabel and set the XTickLabelRotation directly, no need for text.
참고 항목
카테고리
Help Center 및 File Exchange에서 Bar Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!