我如何获得具有功能bar3和每个条的不同宽度的条形图?

时间:2014-06-17 17:02:15

标签: matlab graphics graph width matlab-figure

我有代码:

values = [1.0 0.6 0.1;  0.0 1.0 0.3;  0.9 0.4 1.0];
h = bar3(values);
shading interp
for i = 1:length(h)
    % Get the ZData matrix of the current group
    zdata = get(h(i),'Zdata');
    set(h(i),'Cdata',zdata)
end
set(h,'EdgeColor','k')
view(-61, 68);
colormap cool
colorbar

这就是这个数字的样子:

enter image description here

我想根据条形的高度为每个条形获得不同的宽度。

我想要的内容看起来像http://www.sdtools.com/help/ii_mac.html中的图片。

blah http://www.sdtools.com/help/mac.gif

2 个答案:

答案 0 :(得分:7)

这有点难以弄清楚,但是一旦你得到这个模式就很容易了。每个'XData'的{​​{1}}和'YData'属性是定义每个条的x和y宽度的矩阵。每组6行的那些矩阵定义了一个条形。因此,诀窍是根据h(i)修改'XData''YData'

values

enter image description here

请注意,上述代码根据values = [1.0 0.6 0.1; 0.0 1.0 0.3; 0.9 0.4 1.0]; h = bar3(values); m = max(values(:))*2; %// normalizing constant for bar width shading interp for i = 1:length(h) % Get the ZData matrix of the current group xdata = get(h(i),'Xdata'); ydata = get(h(i),'Ydata'); zdata = get(h(i),'Zdata'); set(h(i),'Cdata',zdata) for k = 1:6:size(xdata,1) xdatak = xdata(k+(0:5),:); xdatak = round(xdatak)+sign(xdatak-round(xdatak))*values(ceil(k/6),i)/m; xdata(k+(0:5),:) = xdatak; ydatak = ydata(k+(0:5),:); ydatak = round(ydatak)+sign(ydatak-round(ydatak))*values(ceil(k/6),i)/m; ydata(k+(0:5),:) = ydatak; end set(h(i),'XData',xdata); set(h(i),'YData',ydata); end set(h,'EdgeColor','k') view(-61, 68); colormap cool colorbar 缩放线性大小(宽度)。要缩放区域,只需使用values的平方根:

values

在上述任何一种情况下,如果您希望所有高度相等的条形仅用

替换第二条线
values = [1.0 0.6 0.1;  0.0 1.0 0.3;  0.9 0.4 1.0];
h = bar3(values);
svalues= sqrt(values);
m = max(svalues(:))*2; %// normalizing constant for bar width
shading interp
for i = 1:length(h)
    % Get the ZData matrix of the current group
    xdata = get(h(i),'Xdata');
    ydata = get(h(i),'Ydata');
    zdata = get(h(i),'Zdata');
    set(h(i),'Cdata',zdata)
    for k = 1:6:size(xdata,1)
        xdatak = xdata(k+(0:5),:);
        xdatak = round(xdatak)+sign(xdatak-round(xdatak))*svalues(ceil(k/6),i)/m;
        xdata(k+(0:5),:) = xdatak;
        ydatak = ydata(k+(0:5),:);
        ydatak = round(ydatak)+sign(ydatak-round(ydatak))*svalues(ceil(k/6),i)/m;
        ydata(k+(0:5),:) = ydatak;
    end
    set(h(i),'XData',xdata);
    set(h(i),'YData',ydata);
end
set(h,'EdgeColor','k')
view(-61, 68);
colormap cool
colorbar

或者如果您更喜欢2D视图,请使用

h = bar3(ones(size(values)));

enter image description here

答案 1 :(得分:4)

只是为了好玩,这是问题的二维解决方案:

values=values./max(values(:)); % normalize to 1
cmap=cool(numel(unique(values(:)))); % set color map range
hold on
for n=1:numel(values)
    [x y]=ind2sub(size(values),n);
    revec(n,:)=[x-0.5*values(n) y-0.5*values(n) values(n) values(n)];
    try
        rectangle('Position',revec(n,:),'FaceColor',cmap( round(values(n)*size(cmap,1)),:))
    end
end

enter image description here