# Box plot with categorical axis - without LaTex interpreter

조회 수: 7(최근 30일)
Achuan Chen 2021년 12월 13일
댓글: Achuan Chen 2021년 12월 17일
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:
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표시숨기기 이전 댓글 수: 1
Achuan Chen 2021년 12월 13일
I've atteached it. Sorry I forgot to do so.

댓글을 달려면 로그인하십시오.

### 채택된 답변

dpb 2021년 12월 14일
편집: dpb 2021년 12월 14일
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
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표시숨기기 없음
Achuan Chen 2021년 12월 17일
Sensational. Helps out a Matlab newbie like me a lot, thank you sir!

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!

Translated by