如何保持Matlab绘图原尺寸,将图例移至其他子图或指定位置?
MATLAB图例位置调整方案(保持绘图原始尺寸)
你的图表包含12条数据线,实线对应左侧Y轴(L)数据,虚线对应右侧Y轴(R)数据,需要在不改变绘图本身尺寸的前提下,将图例移至图表上方、下方或其他子图,以下是具体实现方法:
一、将图例放在图表上方/下方(不占用绘图区域)
通过指定图例的Location参数为外部位置(如northoutside或southoutside),配合NumColumns调整图例列数,同时强制锁定绘图区域的位置,避免图例挤压绘图空间。
修改后的示例代码:
%% 创建12组随机数据,6组对应左Y轴,6组对应右Y轴 x = linspace(1,5,100); datY_Left ={normrnd(2,2,size(x)),normrnd(5.5,3,size(x)),normrnd(4,4.5,size(x)),normrnd(3.5,3,size(x)),normrnd(2,2,size(x)),normrnd(3.2,1.8,size(x))}; nameYL = {'Data1,YLeft','Data2,YLeft','Data3,YLeft','Data4,YLeft','Data5,YLeft','Data6,YLeft'}; colorYL = {'c','m','r','k','b','g'}; datY_Right = {normrnd(1.5,2,size(x)),normrnd(3,3,size(x)),normrnd(2,4.5,size(x)),normrnd(3,3,size(x)),normrnd(2.5,2,size(x)),normrnd(3,1.5,size(x))}; nameYR = {'Data1,YRight','Data2,YRight','Data3,YRight','Data4,YRight','Data5,YRight','Data6,YRight'}; colorYR = {'c','m','r','k','b','g'}; %% 绘图并调整图例位置 figure; yyaxis left hold on for m = 1:length(datY_Left) plot(x,datY_Left{m},'-','Color',colorYL{m},'DisplayName',nameYL{m}); set(gca,'YLim',[-5 10]); end yyaxis right hold on for m = 1:length(datY_Right) plot(x,datY_Right{m},'--','Color',colorYR{m},'DisplayName',nameYR{m}); set(gca,'YLim',[-10 10]); end hold off % 图例放在图表上方 lgd = legend('-DynamicLegend', 'Location', 'northoutside'); set(lgd, 'NumColumns', 2); % 锁定绘图区域位置,确保尺寸不变 pos = get(gca,'Position'); set(gca,'Position',pos); % 若要将图例放在下方,替换上述图例代码为: % lgd = legend('-DynamicLegend', 'Location', 'southoutside'); % set(lgd, 'NumColumns', 2);
二、将图例移至其他子图
创建子图布局,把主绘图放在一个子图,图例单独放在另一个空白子图中,完全不占用主绘图的空间:
%% 创建12组随机数据(与上方数据源一致) x = linspace(1,5,100); datY_Left ={normrnd(2,2,size(x)),normrnd(5.5,3,size(x)),normrnd(4,4.5,size(x)),normrnd(3.5,3,size(x)),normrnd(2,2,size(x)),normrnd(3.2,1.8,size(x))}; nameYL = {'Data1,YLeft','Data2,YLeft','Data3,YLeft','Data4,YLeft','Data5,YLeft','Data6,YLeft'}; colorYL = {'c','m','r','k','b','g'}; datY_Right = {normrnd(1.5,2,size(x)),normrnd(3,3,size(x)),normrnd(2,4.5,size(x)),normrnd(3,3,size(x)),normrnd(2.5,2,size(x)),normrnd(3,1.5,size(x))}; nameYR = {'Data1,YRight','Data2,YRight','Data3,YRight','Data4,YRight','Data5,YRight','Data6,YRight'}; colorYR = {'c','m','r','k','b','g'}; %% 创建子图布局:主图+图例子图 figure; % 主绘图子图 ax1 = subplot(1,2,1); yyaxis left hold on for m = 1:length(datY_Left) plot(x,datY_Left{m},'-','Color',colorYL{m},'DisplayName',nameYL{m}); set(ax1,'YLim',[-5 10]); end yyaxis right hold on for m = 1:length(datY_Right) plot(x,datY_Right{m},'--','Color',colorYR{m},'DisplayName',nameYR{m}); set(ax1,'YLim',[-10 10]); end hold off % 图例专用子图(隐藏坐标轴) ax2 = subplot(1,2,2); set(ax2,'Visible','off'); % 将主图的图例移至该子图 lgd = legend(ax1,'-DynamicLegend','Location','center'); set(lgd, 'NumColumns', 1); % 调整主图宽度,确保绘图尺寸不变 pos1 = get(ax1,'Position'); pos1(3) = pos1(3)*0.7; set(ax1,'Position',pos1);
内容的提问来源于stack exchange,提问作者sangnv
相关产品推荐
相关产品推荐

