Box plot with categorical axis - without LaTex interpreter

6 views (last 30 days)
Achuan Chen
Achuan Chen on 13 Dec 2021
Commented: Achuan Chen on 17 Dec 2021
I have a box plot for the prices of 8 different varieties of apples, the 8 distinct varieties are contained in 'variety' column of S_apples
I would like to label the x-axis by those 8 varieties.
Here's my code:
T=readtable('fruitvegprices2.csv');
items={'apples','pears','carrots','cabbage'};
%apples
[idx,ia] = ismember(T.(2),items{1});
T_apples = T(idx,{'item','variety'});% this gives table of apples alone
S_apples=unique(T_apples,'stable') %distinct varieties of apples
A=sortrows(T(idx,{'variety','price'})) %grouping the varieties together
C=cell(length(S_apples.variety),1);%column i=prices of variety i
for i=1:length(S_apples.variety)
[c,d]=ismember(A.variety,S_apples.(2){i});
for k=1:length(A(c,:).price)
C{k,i}=A(c,:).price(k);
end
end
C(find(cellfun(@isempty,C)))={nan};
boxchart(cell2mat(C))
xlabel('Variety')
ylabel('Price')
I've tried creating categorical variables:
axis=categorical(cell2mat(C),1:8,S_apples.variety);
plot=boxchart(axis,cell2mat(C))
but it doesn't seem to work, it says: passing xgroup data isn't supported when ydata is a matrix.
How can I fix this?
Thank you very much!
  2 Comments

Sign in to comment.

Accepted Answer

dpb
dpb on 14 Dec 2021
Edited: dpb on 14 Dec 2021
Much easier now... :)
optFV=detectImportOptions('fruitvegprices.csv') % lets you then set the input variable type
optFV.VariableTypes(contains(optFV.VariableTypes,'char'))={'categorical'}; % to categorical for the string data
tFV=readtable('fruitvegprices.csv',optFV); % then use import object to read table
ia=tFV.item=='apples'; % select apples only
boxplot(tFV.price(ia),tFV.variety(ia)) % and then plot them
hAx=gca; % get the axes handle
hAx.XTickLabelRotation=45; % so can read labels
Moral -- primarily is one of "use the table, Luke!" :) Once you have a table, use the addressing modes to select data from the table as needed; don't waste time, code and memory creating all kinds of superfluous variables that are just copies of the data you already have.
There's a link at bottom of the reference page on the table data type that outlines all the myriad addressing syntax options.
Also, for data such as these, you'll want to explore groupsummary, rowfun and the general category of grouping variables and the splitapply workflow.
  1 Comment
Achuan Chen
Achuan Chen on 17 Dec 2021
Sensational. Helps out a Matlab newbie like me a lot, thank you sir!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by