【问题标题】:Multiple boxplot with unequal length in MATLABMATLAB中长度不等的多个箱线图
【发布时间】:2021-05-02 20:45:49
【问题描述】:

下面是我用来在一个图中绘制多个箱线图的 MATLAB 代码。但是,这仅适用于数据长度相等的情况(本例中为 n1,n2,n3,n4,n5,n6 =10)。如何更改它以使其适用于长度不等的数据集?例如:n1=10,n2=10,n3=15,n4=15,n5=5,n6=5?

clc 
clear 
n1=10;n2=10;n3=10;n4=10;n5=10;n6=10;
x=[rand(1,n1) rand(1,n2) rand(1,n3) rand(1,n4) rand(1,n5) rand(1,n6)]; 
n=10 ; xx=([1:6])'; % example 
r=repmat(xx,1,n)'; 
g=r(:)'; 


positions = [1 2 3 4 5 6 ]; 
h=boxplot(x,g, 'positions', positions); 
set(h,'linewidth',2) 

set(gca,'xtick',[mean(positions(1:2)) mean(positions(3:4)) mean(positions(5:6)) ]) 
set(gca,'xticklabel',{'exp1','exp2','exp3'},'Fontsize',28) 

color = ['c', 'y', 'c', 'y','c', 'y']; 
h = findobj(gca,'Tag','Box'); 
for j=1:length(h) 
patch(get(h(j),'XData'),get(h(j),'YData'),color(j),'FaceAlpha',.5); 
end 

【问题讨论】:

  • hold on循环调用boxplot
  • 你能举个例子吗?它对我不起作用。
  • 你尝试了什么,什么没用?
  • 我不确定如何对不平衡数据使用保持循环。你能帮忙吗?
  • 不存在“保持循环”

标签: matlab matlab-figure boxplot


【解决方案1】:
clearvars
n1=10;n2=10;n3=15;n4=15;n5=5;n6=5;
A=zeros(n1,1);A=num2str(A);A(1:end)='1';
B=zeros(n1,1);B=num2str(B);B(1:end)='2';
C=zeros(n1,1);C=num2str(C);C(1:end)='3';
D=zeros(n1,1);D=num2str(D);D(1:end)='4';
E=zeros(n1,1);E=num2str(E);E(1:end)='5';
F=zeros(n1,1);F=num2str(F);F(1:end)='6';
x=[rand(1,n1) rand(1,n2) rand(1,n3) rand(1,n4) rand(1,n5)   rand(1,n6)];
boxplot([x(1,1:n1)';x(1,n1+1:n1+n2)';x(1,n1+n2+1:n1+n2+n3)';x(1,n1+n2+n3+1:n1+n2+n3+n4)';...
x(1,n1+n2+n3+n4+1:n1+n2+n3+n4+n5)';x(1,n1+n2+n3+n4+n5+1:n1+n2+n3+n4+n5+n6)'],[A;B;C;D;E;F])

【讨论】:

  • 请不要在没有解释的情况下发布代码块 - 包括它如何解决问题的描述。
【解决方案2】:

您的代码有几个问题会导致它失败。检查我下面的代码,您应该可以用您的代码替换它。不必指定 n1,n2,...等,而是将所有 n 值放在一个数组中。请注意,如果您将 ns 中的元素数量从 6 更改为 6,您的 set 函数将不起作用,但我的代码会自行运行。将来,我建议将您的代码概括为更少依赖这些东西,并定义更少的变量。

ns=[20,7,16,5,6,7]; %rather than specifying all your n variables individually, put them in an array
x=rand(1,sum(ns(:))); %allocates membory for x
ns=[0,ns]; %used for easier indexing in for loop
for(i=2:length(ns))
    g((1+sum(ns(1:(i-1)))):(ns(i)+sum(ns(1:(i-1)))))=repmat(i-1,1,ns(i)); % populates g array
end
positions=1:(length(ns)-1);
h=boxplot(x,g,'positions',positions)

或者,如果它对您更有意义,您可以替换

ns=[0,ns]; %used for easier indexing in for loop
for(i=2:length(ns))
    g((1+sum(ns(1:(i-1)))):(ns(i)+sum(ns(1:(i-1)))))=repmat(i-1,1,ns(i)); % populates g array
end

g=[];
for(i=1:length(ns))
    g=[g repmat(i,1,ns(i))];
end

虽然这通常是不好的做法,因为 g 的大小会随着每个循环而变化,所以如果你的 ns 太大,Matlab 可能会发出警告。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多