フィルターのクリア

Plot bar chart from elements of string

24 ビュー (過去 30 日間)
Madlab
Madlab 2018 年 9 月 26 日
編集済み: Stephen23 2018 年 9 月 26 日
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')

採用された回答

Stephen23
Stephen23 2018 年 9 月 26 日
編集済み: Stephen23 2018 年 9 月 26 日
>> [U,~,X] = unique(thecountry);
>> cnt = histc(X,1:numel(U));
>> bar(cnt)
creates this:
You might want to read this too:
  2 件のコメント
Madlab
Madlab 2018 年 9 月 26 日
Thank you very much for your input. What I am trying to plot is more like this image here, showing the counts for each respective country. That is why I am trying to utilise the loop to count each country and plot it.
Stephen23
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:
With newer MATLAB versions you can simply add the names as XTickLabel and set the XTickLabelRotation directly, no need for text.

サインインしてコメントする。

その他の回答 (1 件)

jonas
jonas 2018 年 9 月 26 日
編集済み: jonas 2018 年 9 月 26 日
something like this?
n=ones(size(thecountry))
[G,ctr]=findgroups(thecountry)
nrupt=splitapply(@sum,n,G)
bar(nrupt)
set(gca,'xtick',1:size(nrupt,1),'xticklabel',ctr,'xticklabelrotation',90,'fontsize',7,'ticklength',[0 0])

カテゴリ

Help Center および File ExchangeLine Plots についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by