Box plot - plotting multiple datasets on one plot

조회 수: 17 (최근 30일)
Duncan Wright
Duncan Wright 2017년 11월 12일
편집: dpb 2017년 11월 12일
Following the documentation I'm unable to get 4 datasets plotted on whisker a plot.
My 4 dataset are called Bheading, Bheading1, Bheading2 and Bheading3.
My code is as follows:
boxplot([Bheading,Bheading1,Bheading2,Bheading3],'Notch','on','Labels',{'dataset1','dataset2',dataset3',dataset4'},'Whisker',1)
This gives me this error: There must be the same number of labels as groups or as the number of elements in X.
If I try to just plot the datasets without labels (like this):
boxplot([Bheading,Bheading1,Bheading2,Bheading3]
Only one box plot appears.
Thanks in advance.

답변 (1개)

dpb
dpb 2017년 11월 12일
편집: dpb 2017년 11월 12일
Well, you're not following the documentation precisely which says "If X is a matrix, there is one box per column; if X is a vector, there is just one box."
So, in the first case you'd have to have a label for every element in the vector and there would only be a single point for each; in the latter it did precisely what the doc says it'll do. Build the array by column instead of as a single long vector...
boxplot([Bheading.' Bheading1.' Bheading2.' Bheading3.' ],'Notch','on', ...
'Labels',{'dataset1','dataset2',dataset3',dataset4'},'Whisker',1)
While it isn't specifically the problem, it is in general poor practice to make multiple variables of the same name with subsequent indices as identifiers; use an array and indexing instead. Then such code and any other operations is/are much simpler to write and can take advantage of the power of Matlab in vector operations.
data = [Bheading.' Bheading1.' Bheading2.' Bheading3.']; % one array from multiple vectors
boxplot(data,'Notch','on','Labels',{'dataset1','dataset2',dataset3',dataset4'},'Whisker',1)
It would be best practice to create the array in the initial step(s) of the script/function rather than as shown above after having multiple names but we don't have enough information to know from whence the data came to provide specifics.

Community Treasure Hunt

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

Start Hunting!

Translated by