The NaN
(Not a Number) 值可能是一件烦人的事情,但在某些情况下也是一件方便的事情。
当你绘制数据时,Matlab 会在每个没有值的数据点处留下空白(NaN
)。所以原理就是插入这些NaN
之间的数据集并告诉 Matlab 绘制全部数据。凡是有的地方Matlab都会自动留空NaN
.
这是一个示例,因为您没有提供示例数据,所以我首先必须定义 3 个简短的数据集,类似于您图中的数据集:
%% // sample data sets
yf = @(x) 2*x+40+randi(7,size(x)) ;
x1 = 57:61 ; y1 = yf(x1) ;
x2 = 72:76 ; y2 = yf(x2) ;
x3 = 80:83 ; y3 = yf(x3) ;
这是经过编辑的答案,考虑了 Y 轴的中断。为了能够对数据集调用全局操作,我必须将它们重新组合成元胞数组或结构。结构方法将在不同的数据集上使用循环,而元胞数组允许使用cellfun
来压缩代码。我选择了这种方法并使用cellfun
广泛地。
所以第一步是将所有数据集放入元胞数组中
%% // have to group the data sets in a cell array or structure to implement global operations
xc = { x1 ; x2 ; x3 } ;
yc = { y1 ; y2 ; y3 } ;
现在是重的部分:
%// find the maximum vertical span of the datasets and the total span
maxVal = cellfun(@max,yc) ;
minVal = cellfun(@min,yc) ;
maxYspan = max( maxVal-minVal ) ;
totalSpan = max(maxVal)-min(minVal) ;
%// find a sensible Y value to add between the datasets, not too wide but
%// enough to see a break`
yBreakIncrement = round( totalSpan / 10 ) ; %// adjust that if necessary
yTickIncrement = round( maxYspan /5 ) ; %// adjust that if necessary
%% // rebuild the Y datasets
%// value to substract to each data set to bring them together (including the break space)
setSubstract = [0 ; cumsum( (minVal(2:end)-maxVal(1:end-1))- yBreakIncrement ) ] ;
%// get 3 new data sets brought together
Yall = cellfun(@minus , yc , num2cell(setSubstract) , 'uni',0) ;
%// concatenate the data sets, inserting NaN in the middle
Yall = cellfun( @(a,b) cat(2,a,b) , Yall , repmat({NaN},length(yc),1) , 'uni',0) ;
Yall = cat( 2, Yall{:} ) ;
%// remove the last trailing NaN
Yall(end) = [] ;
%% // Build the Y labels
%// generate ticks that covers each interval
Y_tickpos = cellfun(@colon, num2cell(minVal), repmat({yTickIncrement},length(yc),1) , num2cell(maxVal) , 'uni',0) ;
%// generate the Y labels based the real Y values
Y_labels = cellstr( num2str( cat(2, Y_tickpos{:} ).') ) ; %'// ignore this comment
%// now adjust the actual position
Y_tickpos = cellfun(@minus , Y_tickpos , num2cell(setSubstract) , 'uni',0) ;
Y_tickpos = cat( 2, Y_tickpos{:} ) ;
%% // Build the X labels (and axis)
%// create a continuous index for the X axis
X = 1:length(Yall) ;
X_labels = cellstr( num2str( cat(2, xc{:} ).') ) ; %'// generate the X labels based the X values
X_tickpos = X(~isnan(Yall)) ; %// prepare a vector for the label positions
%% // Display
plot(X,Yall) %// plot as usual
%// Set the labels at the chosen positions
set(gca, 'XTick' , X_tickpos , 'XTickLabel' , X_labels )
set(gca, 'YTick' , Y_tickpos , 'YTickLabel' , Y_labels )
That should give you something like:
希望足以让您开始。尝试使该原理适应您的数据。