Count strings occurrences and plot histogram

别来无恙 提交于 2019-12-01 16:37:34

问题


Is there any straightforward way to create a histogram from a cell array like the one below? The spacing between the consecutive bars should be exactly the same and the labels of the x-axis should be the corresponding names of the variables below in a vertical orientation.

'w464'
'w462'
'w461'
'w464'
'w461'
'w463'
'w466'
'w461'

回答1:


I would like to know a better way, as well. Fwiw, I have used countmember in a roundabout way to plot data like this. I.E. if the data you posted was named A

>> B={sort(unique(A)) countmember(sort(unique(A)),A)};
>> bar(B{2});
>> set(gca,'XTickLabel',B{1})



回答2:


If you have access to the statistics toolbox, grp2idx is very useful:

%# sorting is only necessary if the output should be sorted as well
[idx,label] = grp2idx(sort(A)) 

hist(idx,unique(idx));
set(gca,'xTickLabel',label)



回答3:


A solution that only uses built-in functions

[u,~,n] = unique(A(:));
B = accumarray(n, 1, [], @sum);
bar(B)
set(gca,'XTickLabel',u)



回答4:


You can also use the histogram function as follows:

[C,~,ic] = unique(A);

fig1 = figure;
axes1 = axes('Parent',fig1,'XTickLabel',C,'XTick',1:length(C));
hold(axes1,'on');

histogram(ic)


来源:https://stackoverflow.com/questions/11967154/count-strings-occurrences-and-plot-histogram

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!