如何在里面绘制带有文字标签的饼图?

时间:2014-05-28 07:26:45

标签: matlab drawing matlab-figure pie-chart labels

如何在内部绘制带有文本标签的饼图(如果它可以放在相应饼图的中心位置,会更好)?

要清楚,我想创建这样的东西,目前我必须在图窗口中手动编辑它。

默认情况下,我只能得到这个(即饼图聊天之外的文字标签):


编辑:我目前的代码:

%% data
data_raw = [68 58];
data = [100-data_raw' data_raw'];


%% draw here
figure

subplot(1,2,1)
h = pie(data(1, :)); % 2D pie chart
hp = findobj(h, 'Type', 'patch');
set(hp(1),'FaceColor',[165/255 165/255 165/255]);
set(hp(2),'FaceColor',[90/255 155/255 213/255]);

subplot(1,2,2)
h2 = pie(data(2, :)); % 2D pie chart
hp2 = findobj(h2, 'Type', 'patch');
set(hp2(1),'FaceColor',[165/255 165/255 165/255]);
set(hp2(2),'FaceColor',[90/255 155/255 213/255]);

2 个答案:

答案 0 :(得分:1)

根据我的评论,它会导致:

%% data
data_raw = [68 58];
data = [100-data_raw' data_raw'];


%% draw here
figure

subplot(1,2,1)
h = pie(data(1, :)); % 2D pie chart
hp = findobj(h, 'Type', 'patch');
set(hp(1),'FaceColor',[165/255 165/255 165/255]);
set(hp(2),'FaceColor',[90/255 155/255 213/255]);

subplot(1,2,2)
h2 = pie(data(2, :)); % 2D pie chart
hp2 = findobj(h2, 'Type', 'patch');
set(hp2(1),'FaceColor',[165/255 165/255 165/255]);
set(hp2(2),'FaceColor',[90/255 155/255 213/255]);

hText = findobj(h,'Type','text');
textPositions_cell = get(hText,{'Position'}); % cell array
textPositions = cell2mat(textPositions_cell); % numeric array
textPositions = textPositions * 0.4; % scale position
set(hText,{'Position'},num2cell(textPositions,[3,2])) % set new position

hText = findobj(h2,'Type','text');
textPositions_cell = get(hText,{'Position'}); % cell array
textPositions = cell2mat(textPositions_cell); % numeric array
textPositions = textPositions * 0.4; % scale position
set(hText,{'Position'},num2cell(textPositions,[3,2])) % set new position

enter image description here

答案 1 :(得分:1)

一种更简单的方法是将当前标签的位置加倍:

%% data
data_raw = [68 58];
data = [100-data_raw' data_raw'];

%% draw here
figure

subplot(1,2,1)
h1 = pie(data(1, :)); % 2D pie chart
h1(1).FaceColor = [165/255 165/255 165/255];
h1(2).Position = 0.5*h1(2).Position;
h1(3).FaceColor = [90/255 155/255 213/255];
h1(4).Position = 0.5*h1(4).Position;

subplot(1,2,2)
h2 = pie(data(2, :)); % 2D pie chart
h2(1).FaceColor = [165/255 165/255 165/255];
h2(2).Position = 0.5*h2(2).Position;
h2(3).FaceColor = [90/255 155/255 213/255];
h2(4).Position = 0.5*h2(4).Position;

如上面的代码所示,手柄成对出现,即首先是贴片(馅饼),然后是文本(标签)。因此,对于任意数量的标签,以下内容将起作用:

%% arbitrary number of slices
data = rand(1,5);
labels = {'One','Two','Three','Four','Five'};
pieHandle = pie(data,labels);

%% reposition labels
for iHandle = 2:2:2*numel(labels)
    pieHandle(iHandle).Position = 0.5*pieHandle(iHandle).Position;
end

结果如下:

pie with arbitrary number of slices