Matlab - How to plot 2 different columns of excel data for 2 boxplot under 1 x-axis label?

I m trying to plot 2 different columns of excelsheet data (.xls) "Data1" & "Data2" under 1 x-axis label "Jan" to compare them side by side visually. How do i do it? Would be really happy if someone could advise me on how to do it.
My excel data:
This is what i m trying to attempt but i do not know what to add in my code to do it:
clear all
clc
surveyData = readtable("surveydata_16Dec2022.xlsx");
surveyData(1:447,["SceneCode", "Data1", "Data2"])
tiledlayout(1,2)
ScoreS = [-3, -2, -1, 0, 1, 2, 3];
mnthOrder = ["Jan","Feb","Mar"];
surveyData.SceneCode = categorical(surveyData.SceneCode, mnthOrder);
surveyData.SceneQuestionCompare = categorical(surveyData.SceneCode, mnthOrder);
% Left axes
ax1 = nexttile
boxchart(surveyData.SceneCode, surveyData.Data1);
xlabel(ax1,'Scenes 1~12')
yt = get(gca, 'YTick');
ytx = linspace(min(yt), max(yt), numel(ScoreS));
ytl = sprintfc('%.0f',ScoreS);
ylabel(ax1,'Qn1')
legend('Physical (N=36)')
% Right axes
ax2 = nexttile
boxchart(surveyData.SceneCode, [surveyData.Data2])
xlabel(ax2,'Scenes 1~12')
yt = get(gca, 'YTick'); % Get Y-Tick Values
ytx = linspace(min(yt), max(yt), numel(ScoreS)); % New Y-Tick Values
ytl = sprintfc('%.0f',ScoreS); % New Y-Tick Labels
set(gca, 'YTick',ytx, 'YTickLabel',ytl)
ylabel(ax2,'Qn2')
legend('VR (N=36)')

Risposte (2)

Hello Zhan
I understand that you are trying to plot 2 different columns under 1 x-axis label using ‘boxchart’.
Please refer to the examples in this documentation or execute the following command to open the example
>> openExample('graphics/UseCombinationOfGroupingVariablesExample')
This example shows how to plot boxchat for 2 variables on same x- axis, considering Temperature data for the years 2015 and 2016.
I hope the above example was helpful.

1 Commento

The boxplot function takes in boxplot(xdata, ydata, groupByData). I wanted to put in 2 different columns of data (e.g. cause1, cause2) into the ydata (y-axis) but apparently it only limits me to put in 1 column of data. I do not want the grouping option.
Would appreciate if you have any solution to go around with that!

Accedi per commentare.

@Zhan An: This answer is essentially the same as what you're trying to do (plot two boxcharts for each x-tick):
The idea is to create one boxchart per column of data, and specify the x-location of each boxchart so that one can be a little to the left and one can be a little to the right of the x-tick location.
See if you can adapt it to work with your data. If you have problems, upload your data here (using the paperclip icon).

12 Commenti

Hi Voss,
Right now my boxplot kinda overlayed. Any ideas what i could do to put it side by side like yours?
Below is my code:
G1 = surveyData.question1
G2 = surveyData.question2
figure%(1)
hold on
boxchart(surveyData.SceneCode, G1, 'BoxWidth', 0.3)
boxchart(surveyData.SceneCode, G2, 'BoxWidth', 0.3)
ylabel('Question A')
xlabel('Scenes 1~12')
title("Physical VS VR")
legend('Physical (N=50)', 'VR (N=50)')
Take a look at the code in the link I shared. Try to adapt it to your data.
Any idea which portion of your code changes the alignment of red box to left, and blue box to right? Tried adapting and doesn't seem to work somehow. Not sure if its bcuz my xfield "surveyData.sceneCode" is hindering it :x
Really appreciate your time and effort in responding to my question.
Yes, using "surveyData.sceneCode" as the first input (xgroupdata) in the boxchart calls specifies the category on the x-axis that the boxchart is plotted with. Since both boxchart calls in your code use "surveyData.sceneCode" as the xgroupdata, they will necessarily be lined up with each other.
You have to change the first input to boxchart to an x-coordinate in order to get the boxcharts slightly offset to the left or right, and you have to call boxchart with only one column of ydata at a time, because boxchart will not let you use xgroupdata when ydata is a matrix.
Hello @Voss
Is there any other ways to offset boxchart A to left, boxchart B to right using xdata as xgroupdata and ydata as a matrix? Been trying to figure that out so far...
Thanks a bunch for helping on it so far!
Please upload (using the paperclip icon) the file "surveydata_16Dec2022.xlsx".
clear all
clc
surveyData = readtable("surveydata_16Dec2022.xlsx");
Warning: Column headers from the file were modified to make them valid MATLAB identifiers before creating variable names for the table. The original column headers are saved in the VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.
mnthOrder = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
surveyData.SceneCode = categorical(surveyData.SceneCode, mnthOrder);
G1 = surveyData.HowDoYouFeelAboutTheIntensityOfTheWorkout1_;
G2 = surveyData.HowDoYouFeelAboutTheIntensityOfTheWorkout2_;
figure%(1)
hold on
% convert categorical array to double, to be able to compare it to loop ii below:
codes = double(surveyData.SceneCode);
% also, we'll need to specify the colors, so I grab them from the axes in
% order to use the same as what would've been used in a boxchart with
% multiple boxes, like you had before:
colors = get(gca(),'ColorOrder');
for ii = 1:12
% indices of the ii-th category in the data set:
idx = codes == ii;
% x-coordinate of this category (it's ii, but it has to be a vector the
% same size as idx):
x = ii + zeros(nnz(idx),1);
% plot two boxcharts for this category:
boxchart(x-0.15, G1(idx), 'BoxWidth', 0.3, 'BoxFaceColor',colors(1,:))
boxchart(x+0.15, G2(idx), 'BoxWidth', 0.3, 'BoxFaceColor',colors(2,:))
end
ylabel('Question A')
xlabel('Scenes 1~12')
title("Physical VS VR")
legend('Physical (N=50)', 'VR (N=50)')
Thanks alot it worked! Any idea on how to keep the month label in order instead of from 0, 2, 4, 6, 8, 10, 12, 14? I used mnthOrder and then surveyData.sceneCode to tag them as the label for x-axis.
I used the following method below but the alignment doesn't seem to match with the bar perfectly.
set(gca, ...
'XTick',1:3, ...
'XTickLabel',{"Jan","Feb","Mar"})
You're welcome!
To get the month names on the x-axis, setting the XTick and XTickLabels, as you are doing, is the right way. The XTicks won't align with any bar but instead will be between the two bars for each month.
You can also set the angle at which the x-tick labels are rotated (below I'm using XTickLabelRotation 0 to have horizontal labels).
clear all
clc
surveyData = readtable("surveydata_16Dec2022.xlsx");
Warning: Column headers from the file were modified to make them valid MATLAB identifiers before creating variable names for the table. The original column headers are saved in the VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.
mnthOrder = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
surveyData.SceneCode = categorical(surveyData.SceneCode, mnthOrder);
G1 = surveyData.HowDoYouFeelAboutTheIntensityOfTheWorkout1_;
G2 = surveyData.HowDoYouFeelAboutTheIntensityOfTheWorkout2_;
figure%(1)
hold on
% convert categorical array to double, to be able to compare it to loop ii below:
codes = double(surveyData.SceneCode);
% also, we'll need to specify the colors, so I grab them from the axes in
% order to use the same as what would've been used in a boxchart with
% multiple boxes, like you had before:
colors = get(gca(),'ColorOrder');
for ii = 1:12
% indices of the ii-th category in the data set:
idx = codes == ii;
% x-coordinate of this category (it's ii, but it has to be a vector the
% same size as idx):
x = ii + zeros(nnz(idx),1);
% plot two boxcharts for this category:
boxchart(x-0.15, G1(idx), 'BoxWidth', 0.3, 'BoxFaceColor',colors(1,:))
boxchart(x+0.15, G2(idx), 'BoxWidth', 0.3, 'BoxFaceColor',colors(2,:))
end
set(gca(), ...
'XTick',1:12, ...
'XTickLabel',mnthOrder, ...
'XTickLabelRotation',0)
ylabel('Question A')
xlabel('Scenes 1~12')
title("Physical VS VR")
legend('Physical (N=50)', 'VR (N=50)')
Thanks alot @Voss! You really are a big help for this!
You're welcome! Any other questions, let me know. Otherwise, please "Accept This Answer". Thanks!

Accedi per commentare.

Categorie

Prodotti

Release

R2022a

Tag

Richiesto:

il 15 Dic 2022

Commentato:

il 16 Gen 2023

Community Treasure Hunt

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

Start Hunting!

Translated by