如何在 Matlab 中将原点设置为轴的中心

How to set the origin to the center of the axes in Matlab

当我在 Matlab 中绘制函数 f(x) 时,例如正弦函数,我得到的图形是这样的:

我想用一种完全不同的方式绘制它,比如用 Mathematica 生成的:

记下轴位置(连同刻度)以及 x 和 y 标签位置。

如有任何帮助,我们将不胜感激。

从 MATLAB 2015b 开始(根据 release notes),您可以对 XAxisLocationYAxisLocation 属性 使用 'origin' 选项。所以将此添加到您的代码中:

ax = gca;                        % gets the current axes
ax.XAxisLocation = 'origin';     % sets them to zero
ax.YAxisLocation = 'origin';     % sets them to zero
ax.Box = 'off';                  % switches off the surrounding box
ax.XTick = [-3 -2 -1 0 1 2 3];   % sets the tick marks
ax.YTick = [-1 -0.5 0 0.5 1];    % sets the tick marks

Source

因为并非所有读者都拥有最新版本的 MATLAB,所以我决定让这个答案更笼统一些,所以现在它是一个函数,它获取要操作的图形句柄作为输入,并设置其原点在中间:

function AxesOrigin(figureh)
% set the origin of a 2-D plot to the center of the axes

figureh.Color = [1 1 1];
% get the original properties:
del_props =  {'Clipping','AlignVertexCenters','UIContextMenu','BusyAction',...
    'BeingDeleted','Interruptible','CreateFcn','DeleteFcn','ButtonDownFcn',...
    'Type','Tag','Selected','SelectionHighlight','HitTest','PickableParts',...
    'Annotation','Children','Parent','Visible','HandleVisibility','XDataMode',...
    'XDataSource','YDataSource','ZData','ZDataSource'};
lineprop = figureh.CurrentAxes.Children.get;
lineprop = rmfield(lineprop,del_props);

x = lineprop.XData;
y = lineprop.YData;
old_XTick = figureh.CurrentAxes.XTick;
old_YTick = figureh.CurrentAxes.YTick;
old_Xlim = figureh.CurrentAxes.XLim;
old_Ylim = figureh.CurrentAxes.YLim;

% check that the origin in within the data points
assert(min(x)<0 && max(x)>0 && min(y)<0 && max(y)>0,'The data do not cross the origin')

figureh.CurrentAxes.Children.delete
axis off

% Create Q1 axes
axes('Parent',figureh,...
    'Position',[0.5 0.5 0.4 0.4],...
    'XTick',old_XTick(old_XTick>0),...
    'YTick',old_YTick(old_YTick>0));
xlim([0 max(old_XTick)]);
ylim([0 max(old_YTick)]);

% Create Q3 axes
axes1 = axes('Parent',figureh,...
    'YAxisLocation','right',...
    'XAxisLocation','top',...
    'Position',[0.1 0.1 0.4 0.4],...
    'XTick',old_XTick(old_XTick<0),...
    'YTick',old_YTick(old_YTick<0));
xlim(axes1,[min(old_XTick) 0]);
ylim(axes1,[min(old_YTick) 0]);

% Create real axes
axes2 = axes('Parent',figureh,...
    'Position',[0.1 0.1 0.8 0.8]);
hold(axes2,'on');
axis off

plot(x,y,'Parent',axes2)
set(axes2.Children,lineprop)
xlim(axes2,old_Xlim);
ylim(axes2,old_Ylim);
end

它删除了原始轴并放置了另外两个以创建一个 'origin-like' 视图。它并不完美,更像是解决方法的基本想法,应该针对特定目的进行调整,但如果您 运行 2015a 或更早,它可能是一个很好的起点。

示范:

x=-2*pi:0.1:2*pi;
h = figure();
plot(x,sin(x),':or');

此代码创建此输出:

并且在使用上面的函数之后:

AxesOrigin(h)

我们得到结果:

这对我有用:

ha = gca;
ha.XAxisLocation = 'origin';
ha.YAxisLocation = 'origin';

基于帮助页面 "Display Axis Lines Through Origin" https://www.mathworks.com/help/matlab/creating_plots/display-axis-lines-through-origin.html