【发布时间】:2025-11-27 16:35:01
【问题描述】:
我如何垂直偏移stem 图,以便茎从 y == 0.5 而不是从 x 轴发出?
我知道我可以更改 x-tick-marks,但最好只更改情节。
stem(X+0.5) 不起作用,因为它只会使茎变长。
我也有正面和负面的数据。而且我在同一轴上还有其他图,我不想偏移。
根据 Luis Mendo 在下面的回答,我为此编写了一个函数(但是请参阅 my answer below,因为 MATLAB 实际上对此有一个内置属性):
function stem_offset(x_data, y_data, offset, offset_mode, varargin)
%STEM_OFFSET stem plot in which the stems begin at a position vertically
%offset from the x-axis.
%
% STEM_OFFSET(Y, offset) is the same as stem(Y) but offsets all the lines
% by the amount in offset
%
% STEM_OFFSET(X, Y, offset) is the same as stem(X,Y) but offsets all the
% lines by the amount in offset
%
% STEM_OFFSET(X, Y, offset, offset_mode) offset_mode is a string
% specifying if the offset should effect only the base of the stems or
% also the ends. 'base' for just the base, 'all' for the baseand the
% ends. 'all' is set by default
%
% STEM_OFFSET(X, Y, offset, offset_mode, ...) lets call all the stem()
% options like colour and linewidth etc as you normally would with
% stem().
if nargin < 3
offset = 1:length(y_data);
y_data = x_data;
end
if nargin < 4
offset_mode = 'all';
end
h = stem(x_data, y_data, varargin{:});
ch = get(h,'Children');
%Offset the lines
y_lines = get(ch(1),'YData'); %// this contains y values of the lines
%Offset the ends
if strcmp(offset_mode, 'all')
set(ch(1),'YData',y_lines+offset)
y_ends = get(ch(2),'YData'); %// this contains y values of the ends
set(ch(2),'YData',y_ends+offset)
else
set(ch(1),'YData',y_lines+offset*(y_lines==0)) %// replace 0 (i.e. only the start of the lines) by offset
end
end
我现在已经上传到文件交换 (http://www.mathworks.com/matlabcentral/fileexchange/45643-stem-plot-with-offset)
【问题讨论】: