为什么您当前的方法不起作用
您的直觉对我来说是有道理的,但是您使用的 barh 函数并不像您想象的那样工作。具体来说,您错误地解释了该函数的 x 和 y 输入的含义。这些输入是常数值,而不是整个轴。第一个y 输入是指从x = 0 水平延伸的条的端点,第一个x 输入是指水平条在y 轴上的位置。为了说明我的意思,我提供了下面的水平条形图:
您可以在 MATLAB barh 函数的 official documentation 中找到相同的图片。用于生成此条形图的代码也在文档中给出,如下所示:
x = 1900:10:2000;
y = [57,91,105,123,131,150,...
170,203,226.5,249,281.4];
figure;
barh(x, y);
x 数组的各个元素,相当令人困惑的是,在 y 轴上显示为每个条的起始位置。 y 数组的相应 元素是每个条的长度。这就是数组必须具有相同长度的原因,这说明它们不是 x 轴和 y 轴的规范,正如人们可能直观地认为的那样。
解决问题的方法
首先,最简单的方法是使用plot 函数和一组代表浮动条的线手动执行此操作。如果您想绘制带有某种颜色协调的线条,请咨询official documentation 以获取plot 函数 - 我提供的代码(this answer on StackOverflow 的修改版本)只是在之间切换浮动条的颜色红色和蓝色。我试图对代码进行注释,以便清楚每个变量的用途。我在下面提供的代码与您要绘制的浮动条形图相匹配,如果您可以将粗浮动条替换为浮动在绘图上的 2D 线。
我使用您在问题中提供的数据来指定此脚本将输出的浮动水平条 - 代码下方显示了屏幕截图。 Array1 & Array2:[0;1;2;3;4;5;6;Nan;Nan;Nan;Nan;17;18;.....60],这些数组从 0 到 6(长度 = 6)和 17 到 60(长度 = 60 - 17 = 43)。因为从 7 到 16 存在某种“不连续性”,所以我必须为每个数组定义两个浮动条。因此,我的长度数组中的前四个值是[6, 6, 43, 43]。其中第一个6和第一个43对应Array1,第二个6和第二个43对应Array2。认识到这种“不连续性”,Array1 和 Array2 的第一个浮动条的起点是 x = 0,Array1 和 Array2 的第二个浮动条的起点是 x = 7。综上所述,您将得到floating_bars 数组[0 0; 0 1.5; 17 0; 17 1.5] 中前四个点的 x 坐标。此数组中的 y 坐标仅用于区分 Array1、Array2 等。
代码:
floating_bars=[0 0; 0 1.5; 17 0; 17 1.5; 20 6; 20 7.5]; % Each row is the [x,y] coordinate pair of the starting point for the floating bar
L=[6, 6, 43, 43, 40, 40]; % Length of each consecutive bar
thickness = 0.75;
figure;
for i=1:size(floating_bars,1)
curr_thickness = 0;
% It is aesthetically pleasing to have thicker bars, this makes the plot look for like the grouped horizontal bar graph that you want
while (curr_thickness < thickness)
% Each bar group has two bars; set the first to be red, the second to be blue (i.e., even index means red bar, odd index means blue bar)
if mod(i, 2)
plot([floating_bars(i,1), floating_bars(i,1)+L(i)], [floating_bars(i,2) + curr_thickness, floating_bars(i,2) + curr_thickness], 'r')
else
plot([floating_bars(i,1), floating_bars(i,1)+L(i)], [floating_bars(i,2) + curr_thickness, floating_bars(i,2) + curr_thickness], 'b')
end
curr_thickness = curr_thickness + 0.05;
hold on % Make sure that plotting the current floating bar does not overwrite previous float bars that have already been plotted
end
end
ylim([ -10 30]) % Set the y-axis limits so that you can see more clearly the floating bars that would have rested right on the x-axis (y = 0)
输出:
我如何使用barh 函数做到这一点?
简短的回答是您必须手动修改函数。有人已经使用 MATLAB 提供的条形图绘图函数之一做到了这一点,bar3。如果您阅读他们的barNew.m 函数并对其进行一些调整,则可以将在此modified bar3 function 中实现的逻辑重新应用于您的目的。如果您想要一个关于从哪里开始的指针,我建议查看他们如何为绘图上的浮动条指定 z 轴最小值和最大值,并应用相同的逻辑来指定 x 轴最小值和最大值您的 2D 机箱中的浮动条。
我希望这会有所帮助,祝您编码愉快! :)