使用特定标记绘图

时间:2011-06-25 18:03:11

标签: matlab plot gnuplot

我想将一个零和一的矩阵绘制成一个图形,这样每1个我有一个形状像垂直条的标记被画成“|”。这样,当一系列1在同一个x轴上时,看起来像一条长直线。

这个例子说明了我的意图:

给出以下矩阵:

0 0 1 1 0 1 0
0 1 0 1 1 1 0
0 1 0 1 1 1 0
1 0 0 1 1 1 0

我明白了:

Bar Figure

3 个答案:

答案 0 :(得分:4)

编辑:

下面的解决方案虽然比当前接受的解决方案稍长,但它的优势在于它创建了一个LINE对象(如果创建的图形对象较少,则UI性能会更好)。它的工作原理是使用NaN来分隔细分:

%#A = [1 1 1 ; 0 0 0 ; 1 1 1];
A = [
    0 0 1 1 0 1 0
    0 1 0 1 1 1 0
    0 1 0 1 1 1 0
    1 0 0 1 1 1 0
];

%# build line x/y points
[m n] = size(A);
[x y] = meshgrid(1:n, 1:m);    %# grid coordinates
x(~A) = NaN;                   %# place NaNs where A is zero
y(~A) = NaN;
x = [x;NaN(1,n)];              %# separate columns by NaNs
y = [y;NaN(1,n)];
x = [x(:) x(:)]';              %'# add endpoints
y = [y(:) y(:)+1]';            %'#
x = x(:);                      %# linearize
y = y(:);

%# plot
line('XData',x, 'YData',y-0.5, 'Color','k', 'LineStyle','-', 'LineWidth',4)
set(gca, 'XGrid','on', 'Box','on', 'FontSize',8, 'LineWidth',2, ...
    'XLim',[0 n]+0.5, 'YLim',[0 m]+0.5, 'XTick',1:n, 'YTick',1:m, ...
    'YDir','reverse')
%#set(gca, 'XTick',[], 'YTick',[])

enter image description here enter image description here

答案 1 :(得分:3)

解决方案2

这是另一个解决方案,看起来很简单。每个数字由一条垂直线表示。所有在一个情节陈述。

%# create the matrix and get coordinates of 1s.
a = logical([
0 0 1 1 0 1 0
0 1 0 1 1 1 0
0 1 0 1 1 1 0
1 0 0 1 1 1 0]);
[r c] = find(flipud(a));
plot([c c]',[r-0.5 r+0.5]','k-')
xlim([min(c)-0.5 max(c)+0.5])
set(gca,'xtick',[],'ytick',[])
box on

enter image description here


解决方案1 ​​

作为替代方案,您可以使用TEXT函数放置'|'某些坐标处的符号。

[r c] = find(flipud(a));
clf
text(c,r,repmat('|',numel(r),1),'FontSize',70,'hor','center','vert','middle')
xlim([min(c)-0.5 max(c)+0.5])
ylim([min(r)-0.6 max(r)+0.4])
set(gca,'xtick',[],'ytick',[])
box on

缺点是您必须使用字体大小和y轴限制来关闭线条。

enter image description here

旁注:很奇怪,我不能只使用'|'没有repmat。因为这个字符实际上可以分隔不同的字符使用char(124)具有相同的效果。我想知道是否还有其他解决办法。

答案 2 :(得分:1)

这是通过将1转换为显式点并通过它们画一条线来实现它的一种方法:

B=logical([A(1,:);A;A(end,:)]);    %# A is your matrix of 1's and 0's

%# create a mesh of indices
x=1:size(B,2);
y=0:size(A,1)+1;
[X,Y]=meshgrid(x,y);

%# plot the lines
figure(1);clf;hold on
arrayfun(@(i)plot(X(B(:,i),i)',Y(B(:,i),i)','color','k','linewidth',1.25),x)
hold off 
set(gca,'box','on','xlim',[min(x),max(x)]+[-1/2 1/2],...
'ydir','r','ytick',[])

这是你应该得到的:

enter image description here

您可以取消arrayfun,但如果您愿意,我会留给您。

相关问题