【发布时间】:2019-06-03 08:35:58
【问题描述】:
我正在创建一个饼图,理想情况下希望图例水平显示在顶部和/或底部。然而,在几乎所有情况下,这是不可能的,因为传说已经脱离了数字。因此,理想情况下,我希望将图例分成两个(或更多)子图例并将它们单独放置。我知道这不是 MATLAB 中的内置功能(我使用的是 R2017b),但我不确定它是否可以工作?我见过一些人设法用折线图做类似的事情,但我无法让它们适应我的饼图。
示例代码:
% Set up a figure and make it a reasonable size/location.
figure( 1 )
set( gcf, 'Position', [ 350, 150, 750, 750 ] )
% Create a list of items for the food menu (example only).
Menu = { "Egg and Bacon", "Egg, Sausage and becon", "Egg and Spam", ...
"Egg, bacon and Spam", "Egg, bacon, sausage and Spam", ...
"Spam, bacon, sausage and Spam", "Nothing" };
% Estimate the demand for said food items (example only).
Orders = randi( 150, 1, length( Menu ) );
% Make a pie chart showing what ratio the food was ordered.
Pie_Plot = pie( Orders );
% Create two ranges to grab the first and second half of the pie chart's
% patches.
Range_1 = 1 : 2 : ceil( length( Pie_Plot ) / 2 );
Range_2 = Range_1( end ) + 2 : 2 : length( Pie_Plot );
% In an ideal world this would be the first of two legends that would
% display at the same time.
Ideal_Leg_Pt1 = legend( Pie_Plot( Range_1 ), ...
Menu( round( Range_1 / 2 ) ), 'orientation', 'horizontal', ...
'location', 'southoutside' );
% A pause because the method doesn't work so without it, this legend
% won't appear.
pause
% The second half of the ideal legend(s) solution; noting that when this
% is created, the original
% legend is replaced.
Ideal_Leg_Pt2 = legend( Pie_Plot( Range_2 ), ...
Menu( round( Range_2 / 2) ), 'orientation', 'horizontal', ...
'location', 'northoutside' );
% Pause for the same reasons as before.
pause
% This is what I'm currently stuck with; a legend that doesn't fit (I'm
% aware I could make it vertical for example but this looks messy in my
% eyes and I'm trying to avoid it unless there really is no way to make
% the ideal method work).
Current_Leg = legend( Menu, 'orientation', 'horizontal', ...
'location', 'northoutside' );
编辑:
这已被标记为可能重复,但我不认为它是(但是我可能是错的)。我已经查看了已链接到的解决方案,但它们主要是我在我的 OP 中提到的类似的东西,但我无法适应使用饼图。我可以接近(例如,zhqiat 的方法),但我不能让它完全适用于饼图。
在上述示例中,它的工作原理是绘制一些部分,创建一个新轴,然后绘制其余部分;但你不能用饼图做到这一点。我可以接近解决这个问题,但我最终得到了两个不能完美重叠的饼图。这就是为什么我不认为这是一个重复问题的核心;饼图似乎在本质上与常规图不同,许多似乎适用于常规线图的解决方案似乎不适用于饼图(但是,我坦率地承认,我可能只是忽略了一个简单的修改,它会使它们全部工作! )。
上述示例的代码(在我的 OP 中直接放在 Ideal_Leg_Pt1 下,其他所有内容都在删除后):
ax2 = axes('Position',get(gca,'Position'),...
'Visible','off','Color','none');
Second_Pie = pie( Orders );
Ideal_Leg_Pt2 = legend( Second_Pie( Range_2 ), ...
Menu( round( Range_2 / 2) ), 'orientation', 'horizontal', ...
'location', 'northoutside' );
【问题讨论】:
-
this post on matlab answers 似乎包含对您问题的答案。我认为第二个答案(由MattF)会起作用。不过没试过。
-
我已经更新了我的帖子,解释了为什么我认为这不是一个重复的问题(但我可能是错的)@EBH 这看起来很适合我的目的,你能告诉我你是怎么做的吗?成功了吗?
标签: matlab matlab-figure legend pie-chart