How to label X-axis on bar graph?

360 次查看(过去 30 天)
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.
Atanu
Atanu 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