作为第一次尝试,我设法仅使用两个 LINE 在每个点绘制饼图图形对象:一种为圆圈,一种为圆圈内的划分。因此,我们只是绘制未填充的饼图。
这在性能方面非常有效。它是通过使用 NaN
将行分隔成段来实现的。将此与其他建议的解决方案进行比较;如果我们看一下它的 source code ,我们发现它为每个点创建一个轴,并调用 MATLAB 的函数 PIE里面。
我们从一些数据点及其“模糊聚类”开始:
numPoints = 15; numClasses = 5;
%# random 2D points
points = randn(numPoints,2);
%# fuzzy clustering: probabilistic distribution
prob = rand(numPoints,numClasses);
prob = bsxfun(@rdivide, prob, sum(prob,2));
下面是绘制散点饼图的代码:
%# pie parameters
theta = linspace(0, 2*pi, 100); %# steps to approximate a circle
r = min(range(points)) / 10; %# radius (determined based on points spread)
%# pie circles
px = bsxfun(@plus, cos(theta).*r, points(:,1))';
py = bsxfun(@plus, sin(theta).*r, points(:,2))';
px(end+1,:) = NaN; py(end+1,:) = NaN;
%# pie divisions
tt = cumsum(prob,2) .* 2*pi;
qx = cat(3, ...
bsxfun(@plus, cos(tt).*r, points(:,1)), ...
repmat(points(:,1), [1 numClasses]), ...
NaN(numPoints,numClasses));
qy = cat(3, ...
bsxfun(@plus, sin(tt).*r, points(:,2)), ...
repmat(points(:,2), [1 numClasses]), ...
NaN(numPoints,numClasses));
qx = permute(qx, [3 2 1]); qy = permute(qy, [3 2 1]);
%# plot
figure
line(px(:), py(:), 'Color','k')
line(qx(:), qy(:), 'Color','k')
axis equal
在我的第二次尝试中,我成功地使用 PATCH 绘制了彩色饼图。函数在每个圆圈中绘制每个切片。显然,这意味着我们正在创建比以前更多的图形对象......
我们本可以使用相同的 NaN
技术通过单个 PATCH 调用从每个圆绘制相同的切片,但是当饼图重叠时证明是有问题的(特别是 z 顺序不正确) .
clr = hsv(numClasses); %# colors for each class
r = min(range(points)) / 10; %# radius (determined based on points spread)
tt = cumsum(prob,2) .* 2*pi; %# pie divisions
figure
h = zeros(numPoints,numClasses); %# handles to patches
for idx=1:numPoints %# for each point
for k=1:numClasses %# for each class
%# start/end angle of arc
if k>1
t(1) = tt(idx,k-1);
else
t(1) = 0;
end
t(2) = tt(idx,k);
%# steps to approximate an arc from t1 to t2
theta = linspace(t(1), t(2), 50);
%# slice (line from t2 to center, then to t1, then an arc back to t2)
x = points(idx,1) + r .* [cos(t(2)) ; 0 ; cos(t(1)) ; cos(theta(:))];
y = points(idx,2) + r .* [sin(t(2)) ; 0 ; sin(t(1)) ; sin(theta(:))];
h(idx,k) = patch('XData',x, 'YData',y, ...
'FaceColor',clr(k,:), 'EdgeColor','k');
%# show percentage labels
ind = fix(numel(theta)./2) + 3; %# middle of the arc
text(x(ind), y(ind), sprintf('%.2f%%', prob(idx,k)*100), ...
'Color','k', 'FontSize',6, ...
'VerticalAlign','middle', 'HorizontalAlign','left');
end
end
axis equal
labels = cellstr( num2str((1:numClasses)', 'Cluster %d') );
legend(h(1,:), labels)
如果百分比标签太多,只需删除 TEXT在上面调用。
我是一名优秀的程序员,十分优秀!