Data not plotting as a 'stacked' bar chart?
显示 更早的评论
Hi,
I have an some data based on 18 "regions" e.g. Alaska, Central America, Europe etc... stored as a 18x1 categorical. In a separate 18x1 array, I have the counts of each of these regions (e.g. 25 for Europe, 12 for Alaska etc...), with 319 records in total. I also have a 319x1 categorical array of the full dataset of the categories.
I want to plot them as a 'stacked' bar chart, with one bar with all the 319 records, broken down by the region, although currently it plots them as 18 separate bars, regardless of if I use the 'stacked' argument or not. It seems like an easy fix but I've been stuck on it for a while. Any help is appreciated, my current code is below and I've attached the original data file.
Thanks!
clear all
close all
[num,txt,raw]=xlsread('DefCat_All_Erup.xlsx');
Region = raw(2:320,15);
Region = cellstr(Region);
figure(1)
Region=categorical(Region);
Regions_X = categories(Region);
Regions_X = categorical(cellstr(Regions_X));
Regions_Y = countcats(Region);
Regions_Y = Regions_Y.';
bar(Regions_X, Regions_Y,'stacked')
hold off
采纳的回答
更多回答(1 个)
bar is an abomination of an implementation -- it is documented that if the input data are a vector, the 'stacked' option is interpreted the same as if it were 'grouped' -- iow, the designers didn't consider it to be a needed option.
I don't recall if I've been able to mung on it to make it work or not; I've done a lot over the years and continue to harangue Mathworks about the shortcomings, but it's been an uphill struggle get any really significant changes...well, usual rant aside, let's see...
tD=readtable(websave('DefCat_All_Erup.xlsx','https://www.mathworks.com/matlabcentral/answers/uploaded_files/1154913/DefCat_All_Erup.xlsx'));
tD=convertvars(tD,@iscellstr,'categorical');
tD.Properties.VariableNames(15)={'Region'};
regionCounts=countcats(tD.Region).';
% here's the trick -- add a second row of NaN values so bar has an in array
% instead of just a vector. That's enough to make it honor 'stacked' style
% and NaN values are never displayed so nothing unwanted actually shows up
bar([regionCounts;nan(size(regionCounts))],'stacked')
legend(categories(tD.Region),'location','eastoutside')
xticks([])
xlim([-0.2 2.2])
OK, you can fake it by introducing the second row of NaN and then futz around with the xlim values to center the bar.
You can experiment with changing the size of the box with the axes 'Position' property or turn the box off, etc., etc., ...
NOTA BENE: The "nan trick" is an exceedingly useful one with handle graphics in general to create desired effects -- unfortunately, it's rather esoteric and unfortunate have to resort to such artifices, but it is what it is...
类别
在 帮助中心 和 File Exchange 中查找有关 Interactive Control and Callbacks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


