在MATLAB中将y轴上下颠倒

Roo*_*ook 32 matlab

有没有办法在matlab图中颠倒y轴,以便y轴的正方向而不是向上指向?

(求求你了;请不要说,把它打印出来,然后转动纸张;-)

gno*_*ice 54

'YDir'轴属性可以是'normal''reverse'.默认情况下,它适用'normal'于大多数绘图,但某些绘图会自动将其更改为'reverse',例如imageimagesc函数.

您可以使用set函数或点索引设置轴的y轴方向(在较新的MATLAB版本中):

h = gca;  % Handle to currently active axes
set(h, 'YDir', 'reverse');
% or...
h.YDir = 'reverse';
Run Code Online (Sandbox Code Playgroud)

我对其他一些答案感到困惑,他们说该'YDir'物业已经不知何故消失或者出错了.我从2013年,2014年或2016年的MATLAB版本中没有看到任何此类行为.我遇到的只有两个潜在的陷阱:

  • 该属性不能使用单元格数组设置,只能使用字符串:

    >> set(gca, 'YDir', {'reverse'});
    Error using matlab.graphics.axis.Axes/set
    While setting property 'YDir' of class 'Axes':
    Invalid enum value. Use one of these values: 'normal' | 'reverse'.
    
    Run Code Online (Sandbox Code Playgroud)

    虽然这有效:

    set(gca, {'YDir'}, {'reverse'});  % Property name is also a cell array
    
    Run Code Online (Sandbox Code Playgroud)
  • gca在执行点索引时,该函数不能互换地用作句柄(这就是为什么我h在上面的例子中首先将它保存到变量中):

    >> gca.YDir
    Undefined variable "gca" or class "gca.YDir". 
    >> gca.YDir = 'reverse'  % Creates a variable that shadows the gca function
    gca = 
      struct with fields:
    
        YDir: 'reverse'
    
    Run Code Online (Sandbox Code Playgroud)

最后,如果你想要一些代码来切换'YDir'属性而不管它的当前状态是什么,你可以这样做:

set(gca, 'YDir', char(setdiff({'normal', 'reverse'}, get(gca, 'YDir'))));
% or...
h = gca;
h.YDir = char(setdiff({'normal', 'reverse'}, h.YDir));
Run Code Online (Sandbox Code Playgroud)

  • 如果绘图对应于3D绘图,则Y轴通常默认反转(您可以使用`get(gca,'YDir')`进行检查.在这种情况下,请尝试:`set(gca,'YDir' , '正常的');` (3认同)

小智 9

命令

axis ij

也会反转Y轴(x轴以上为负;下方为正).


小智 6

堆栈顶部的解决方案对我不起作用,

  • imagesc(x,y,data) % results in a flipped plot, the y axis is upside down

  • set(gca,'YDir','reverse'); % gives an error

  • axis ij; % still gives the flipped plot

做了以下工作:

imagesc(x,y,data); axis xy;  % results in the correct plot
Run Code Online (Sandbox Code Playgroud)

YDir属性已在我正在使用的matlab版本(2013年及以上版本)中消失.