How to label X-axis on bar graph?
436 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
dpb
le 9 Oct 2022
Modifié(e) : dpb
le 9 Oct 2022
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 commentaires
dpb
le 14 Oct 2022
Modifié(e) : dpb
le 14 Oct 2022
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.
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!