How to label X-axis on bar graph?

조회 수: 360 (최근 30일)
Struggling in MATLAB
Struggling in MATLAB 2022년 10월 9일
편집: dpb 2022년 10월 14일
I want to label a bar graph with a string array. I am using this following piece of code to label them. But it can not convert catStrArray yo categorical.
catStrArray = {'Baseline',splitlines(sprintf('Food deprivation%c(Week1)',newline)), ...
splitlines(sprintf('Food deprivation%c(Week2)',newline)),splitlines(sprintf('Food deprivation%c(Week3)',newline))};
label = categorical(catStrArray);
label = reordercats(label,catStrArray);
set(gca,'xticklabel',label);
If I drop 'splitlines' as follows then I am not getting newline as intended.
catStrArray = {'Baseline',sprintf('Food deprivation%c(Week1)',newline), ...
sprintf('Food deprivation%c(Week2)',newline),sprintf('Food deprivation%c(Week3)',newline)};
What could I change in the code to make it work? I am looking for something like the following.
I have attached the barGraph code for reference.

채택된 답변

dpb
dpb 2022년 10월 9일
편집: dpb 2022년 10월 9일
cats=categorical(["Baseline";compose('Food deprivation(Week%d)',[1:3].')]);
results=randi(20,4,1);
bar(cats,results)
The problem you ran into was not building a column vector of strings; note the .' transpose operator on the [1:3] vector above to make sure had a column vector. Otherwise, character or cell strings are simply catenated when strung together in a row.
It's a very long label for tick labels, though, but I don't think you can embed the \n character in a categorical variable to be interpreted as a newline by the TeX interpreter on labels; you could manage that with xticklabels and building strings to write.
Instead, I'd probably just put the 'Baseline' and 'Week N' on the tick labels and use the xlabel for the rest something like...
cats=categorical(["Baseline";compose('Week %d',[1:3].')]);
bar(cats,results)
xlabel('Fasting Period')
ylabel('Food deprivation Effect')
  댓글 수: 3
dpb
dpb 2022년 10월 14일
편집: dpb 2022년 10월 14일
cats=categorical(["Baseline";compose(['Food Dep\\newline Week %d'],[1:3].')]);
bar(cats,results)
I wasn't thinking before; you don't bury the actual \n in the string but the TeX \newline directive for interpretation to display multiline labels; hence the concern about embedding control characters inside a categorical variable doesn't come into play.
Struggling in MATLAB
Struggling in MATLAB 2022년 10월 14일
Excellent! That worked. Thank you very much!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by