如何垂直偏移stem
图,以便从y == 0.5而不是从x轴发出词干?
我知道我可以改变x刻度标记,但最好只改变绘图。
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)
答案 0 :(得分:3)
以下似乎有效。显然,stem
对象的第一个子项包含垂直线,因此您只需将其YData
属性中的所有0值更改为所需的偏移量:
delta = .5; %// desired offset
h = stem(1:10); %// plot to be offset. Get a handle
ch = get(h,'Children');
yy = get(ch(1),'YData'); %// this contains y values of the lines
set(ch(1),'YData',yy+delta*(yy==0)) %// replace 0 by delta
包含正数据和负数据以及同一轴上的其他图表的示例:
stem(.5:4.5,ones(1,5),'g') %// not to be offset
hold on
h = stem(1:5,[-2 3 -4 1 -1]); %// to be offset
axis([0 5.5 -5 4])
ch = get(h,'Children');
yy = get(ch(1),'YData'); %// this contains y values of the lines
set(ch(1),'YData',yy+delta*(yy==0)) %// replace 0 by delta
答案 1 :(得分:2)
调用stem
后,您可以在茎上画一个白色矩形。
x = 1:10
stem(x)
fudge=0.05
rectangle('Position', [min(x) * range(x)*fudge, 0.5*fudge, range(x)*(1+2*fudge), 0.5-fudge], 'FaceColor', 'w', 'EdgeColor', 'w')
fudge
是为了避免在轴上绘画,并确保覆盖最左边和最右边的茎。
答案 2 :(得分:2)
看来stem
实际上有一个属性,我不知何故错过了!
http://www.mathworks.com/help/matlab/ref/stem.html#btrw_xi-87
e.g。来自文档:
figure
X = linspace(0,2*pi,50)';
Y = (exp(0.3*X).*sin(3*X));
h = stem(X,Y);
set(h,'BaseValue',2);