首页 > 解决方案 > 图形在 MATLAB 的子图中未正确绘制

问题描述

我有一个数据文件,它有 3 列,第一列是数据的字段,或者你可以说不同的索引。第 2 列是 x 轴数据,第 3 列是 y 轴数据。现在我有不同变量的类似数据文件,比如 8 个文件。我想在 MATLAB 中将所有图形绘制在一个图中。对于我的问题,我只显示一个子图。该子图数据文件应为 5 个索引(第一列)绘制 5 个“线图”。但是当我将它绘制为子图时,它只显示 1 个图。这是我在下面的代码:

% open Zdiff Odd Mode data file
fid = fopen('Data_test.txt');
% Read data in from csv file
readData = textscan(fid,'%f %f %f','Headerlines',1,'Delimiter',',');
fclose(fid);

% Extract data from readData
index_Data = readData{1,1}(:,1);
% Identify the unique indices
uni_idx=unique(index_Data);
xData = readData{1,2}(:,1);
yData = readData{1,3}(:,1);


% Plot Data
f = figure;
%Top Title for all the subplots
p = uipanel('Parent',f,'BorderType','none'); 
p.Title = 'Electrical Characteristics'; 
p.TitlePosition = 'centertop'; 
p.FontSize = 14;
p.FontWeight = 'bold';

cla; hold on; grid on, box on;

ax1 = subplot(2,4,1,'Parent',p);
% Loop over the indices to plot the corresponding data
for i=1:length(uni_idx)
   idx=find(index_Data == uni_idx(i));
   plot(xData(idx,1),yData(idx,1))
end

绘图结果如下: 在此处输入图像描述

当我将数据绘制为一个完整的数字时,该图是完美的。但是由于我有很多数据要在一个图中绘制为子图,所以我需要知道我的子图代码中有什么问题。

这是我的整个数据图的代码,没有子图

在绘制代码之前它与以前相同:

% Plot Data
f1 = figure(1);
cla; hold on; grid on;

% Loop over the indices to plot the corresponding data

for i=1:length(uni_idx)
   idx=find(index_Data == uni_idx(i));
   plot(xData(idx,1),yData(idx,1))
end

结果图如下: 在此处输入图像描述

我在子图中的绘图代码有什么问题?谁能帮我吗?

标签: matlabplotgraphmatlab-figuresubplot

解决方案


这是您的命令序列,以及它们的作用:

f = figure;

创建一个空图形,此处尚未定义轴。

cla

清除当前坐标区,因为没有当前坐标区,所以它创建一个。

hold on

在当前坐标区上设置“保持”属性

grid on, box on

设置当前坐标区的一些其他属性

ax1 = subplot(2,4,1,'Parent',p);

创建新轴。因为它覆盖了先前创建的轴,所以将其删除。

plot(xData(idx,1),yData(idx,1))

绘制到当前坐标轴(即由 创建的坐标轴subplot)。这些轴没有设置“保持”属性,因此后续plot命令将覆盖此处绘制的数据。

正如Ander 在评论中建议的那样,解决方案是设置由subplot. 代替:

cla; hold on; grid on, box on;
ax1 = subplot(2,4,1,'Parent',p);

和:

ax1 = subplot(2,4,1,'Parent',p);
hold on; grid on, box on;

(请注意,这cla不是必需的,因为您正在绘制一个新的空图)。


推荐阅读