Plotting Eye Diagram from ADS Data in MATLAB - matlab

I have a data file (Sample_Eye_1.txt) which I obtained from the simulation plot of ADS Keysight. It has 3 fields - "Index", "Time" and "Voltage". Now the eye diagram plot will be voltage vs time. There can be different voltages at the same time at only different index. So index can be seen as a data filter field or similar like that. The plot in ADS simulation is the following
You can see that the line plot is plotted like it is superimposed on different lines.
Now when I plot data in MATLAB voltage vs time, it is not superimposed somehow. This is the plot generated plot of my matlab code which is just simple xy plot.
My MATLAB code:
% open data file
fid = fopen('Sample_Eye_1.txt');
% Read data in from csv file
readData = textscan(fid,'%f %f %f','Headerlines',1,'Delimiter',',');
% Extract data from readData
index_Data = readData{1,1}(:,1);
xData = readData{1,2}(:,1);
yData = readData{1,3}(:,1);
% Plot Data
f1 = figure(1);
cla; hold on; grid on;
%set(gca, 'XTick',[0 5 10 15 20 25 30]);
%set(gca,'XTick',0:0.1e-8:1e-8)
%set(gca,'XTickLabel',0:1:10)
plot(xData,yData,'r-');
title('Eye Diagram')
xlabel('Time(ns)')
ylabel('Density(V)')
Can anyone help me to generate the plot like the plot of ADS simulation plot?
Note: The data is big (around 2.7 Mb). If I truncate the data, the problem cannot be fully understood.

Your code is fine, the problem is due to the way you plot the data.
plot(xData,yData,'r-');
connects all the points with a line segment, this implies that the "holes" of the eye diagram are "closed" when the lines cross them.
You can obtain the expected plot, by simply change the "lines" with "dots"
plot(xData,yData,'r.')
If you want to have a plot more "similar" to the reference one, you can identify the input points with the same index an plot them (again, with "dots") in a loop in which, at each iteration you can change the colot of the dots.
In the following, you can find an updated versin of your code in which the loop is used to plot the data.
Edit to answer the comment
In general, you can specify the color of the marker by setting the color property either by specifying the "name" of the color or its RGB triplet (ref. to the "plot" function documentation for the details).
In your case, the "unique" indices are 16 whike the available "name" of the color are only 8 therefore you have to define the 16 color by defining explicitly the RGB triplet (which can be boring).
Notice, that the most of your data correspond to the first three indices, so, you could define three colors and let the other be random.
In the updated version of the code I've used this approach, defining the matrix dot_color as follows
dot_color=[0 0 .5
.5 .9 .9
0.9 .5 0
rand(length(uni_idx-3),3)]
this means, I've chosed the first three color and used random numbers for the others.
Of course, you can "manually define also the other colors (the value of each entry in the matrix should range between 0 and 1).
fid = fopen('Sample_Eye_1.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
f1 = figure(1);
cla; hold on; grid on;
%set(gca, 'XTick',[0 5 10 15 20 25 30]);
%set(gca,'XTick',0:0.1e-8:1e-8)
%set(gca,'XTickLabel',0:1:10)
% plot(xData,yData,'r-');
% Loop over the indices to plot the corresponding data
% Define the color of the dots
dot_color=[0 0 .5
.5 .9 .9
0.9 .5 0
rand(length(uni_idx-3),3)]
for i=1:length(uni_idx)
idx=find(index_Data == uni_idx(i));
% plot(readData{1,2}(idx,1),readData{1,3}(idx,1),'.')
plot(readData{1,2}(idx,1),readData{1,3}(idx,1),'.','color',dot_color(i,:))
end
title('Eye Diagram')
xlabel('Time(ns)')
ylabel('Density(V)')

Related

Scatter with line segments

I really like scatter()'s ability to automatically color points based on some vector of values, I just want to add colored lines between the points.
The plot in question has time on x-axis, monte-carlo number on y-axis, and then some measured value as the color vector (e.g. number of cars seen in a video frame).
Basically, each point is an update in the system. So calling scatter(time,monte_carlo_number,[],color_vec) plots the points at which there is an update in the system, with color representing some value. This is great, but I would like to add line segments that connect these points, each segment matching the color specified by color_vec.
Basic working example
% Create example data
data = table();
data.time = randsample(1:100, 1000, true)';
data.mc = randsample(1:50, 1000, true)'; % actual monte-carlo run number labels are sorted
data.color_value = randsample(1:10, 1000, true)';
% Create the scatter plot
scatter(data.time, data.mc, [] , data.color_value, 'filled')
colorbar('Ticks', unique(data.color_value))
% Always label your axes
xlabel('Time (s)')
ylabel('Monte-Carlo Run Number')
Below is a screen-shot of what this code might produce. If color_value is the number of cars seen in a video frame, we can see each time this value is updated via the points. However, it is easier for humans to read this plot if there were lines connecting each point to the next with the correct color. This demonstrates to the viewer that this value continues on in time until the next update.
Something like this? I changed the number of samples to 100, and it is already quite a mess, so I don't think this is going to the viewer understand what's plotted.
% Create example data
data = table();
np = 100;
data.time = randsample(1:100, np, true)';
data.mc = randsample(1:50, np, true)'; % actual monte-carlo run number labels are sorted
data.color_value = randsample(1:10, np, true)';
vals = unique(data.color_value).';
cmap = parula(numel(vals));
colors = [];
for k = 1:numel(vals)
ind = find(data.color_value == vals(k));
data_sel{k} = sortrows(data(ind,:));
colors(k,:) = cmap(k,:);
end
figure(1); clf;
% Create the scatter plot
scatter(data.time, data.mc, [] , data.color_value, 'filled')
hold on
for k = 1:numel(vals)
plot(data_sel{k}.time, data_sel{k}.mc, 'Color',colors(k,:))
end
colorbar('Ticks', unique(data.color_value))
% Always label your axes
xlabel('Time (s)')
ylabel('Monte-Carlo Run Number')

Scatterplot matlab

I have some problems with a scatter plot.
I am plotting a matrix containing grades per assignment for students e.g. [assignments x grades], but if more than one student gets the same grade in the same assignment, the points will be on top of each other. I want to add a small random number (between -0.1 and 0.1) to the x- and y-coordinates of each dot.
On the x-axis it should be number of assignments and on the y-axis it should be all the grades.
the grades matrix is defined as a 12x4 matrix
My code looks like this:
n_assignments = size(grades,2); % Total number of assignments.
n_students = size(grades,1); % Total number of student.
hold on; % Retain current plot when adding new plots.
for i = 1:n_assignments % Loop through every assignment.
% Scatter plot of assignment vs grades for that assignment.
% One assignment on every iteration.
scatter(i*ones(1, n_students), grades(i, :), 'jitter', 'on', 'jitterAmount', 0.1);
end
hold off; % Set the hold state to off.
set(gca, 'XTick', 1:n_assignments); % Display only integer values in x-axis.
xlabel('assignment'); % Label for x-axis.
ylabel('grades'); % Label for y-axis.
grid on; % Display grid lines.
But I keep getting the error message:
X and Y must be vectors of the same length.
Please note that the scatter plot jitter is an undocumented
feature. You can also have semi-transparent markers in line and
scatter plots, which could be another alternative to solve your
current problem.
I will cover the scatter 'jitter' feature in this answer.
Note that 'jitter' only affects the x-axis but not the y-axis (more info on Undocumented Matlab).
Have a look at this example I made based on your description:
Suppose you have a class with 20 students and they have completed 5 assignments. The grades for the assignments are stored in a matrix (grades) where the rows are the assignments and the columns are the students.
Then I simply generate a scatter plot of the data in the grades matrix, one row at a time, in a for loop and using hold on to keep all the graphics on the same figure.
n_assignments = 5; % Total number of assignments.
n_students = 20; % Total number of students.
grades = randi(10, n_assignments, n_students); % Random matrix of grades.
hold on; % Retain current plot when adding new plots.
for i = 1:n_assignments % Loop through every assignment.
% Scatter plot of assignment vs grades for that assignment.
% One assignment on every iteration.
scatter(i*ones(1, n_students), grades(i, :), 'jitter', 'on', 'jitterAmount', 0.1);
end
hold off; % Set the hold state to off.
set(gca, 'XTick', 1:n_assignments); % Display only integer values in x-axis.
xlabel('assignment'); % Label for x-axis.
ylabel('grades'); % Label for y-axis.
grid on; % Display grid lines.
This is the result:
If you still want to add jitter in the y-axis, you would have to do that manually by adding random noise to your grades data, which is something I personally wouldn't recommend, because the grades in the scatter plot could get mixed, thus rendering the plot completely unreliable.

Matlab - plot and color samples based on data

I have the following data:
dataMatrix (20x210): 20 samples with 210 variables each
wavelength: 1 row of 210 variables describing the wavelength number
concentrations: concentration value for each sample (20 rows and 1 column)
I usually plot the data in a normal way:
plot(wavelength, dataMatrix)
But what I want is to plot and color each sample according to the concentration value taking into account the rest, color based on data. I think it is something to do with colormap. The result would be something like this:
Is there any easy way to do this using Matlab?
Thank you very much!
plot accepts line property including line color, like
plot(wavelength, dataMatrix, 'Color', [0,0,0.1])
colormap can convert built-in color maps to RGB matrices, like
nlines = length(concentrations);
cmap = hsv(nlines)
mapping concentration to color could be as easy as sorting the numbers
c = concentrations - min(concentrations);
c = ceil( c/max(c)*nlines );
finally, draw each line separately
for ii = 1:nlines
plot(wavelength, dataMatrix(ii,:), 'Color', cmap(c(ii),:))
hold on
end
hold off

Contour Plotting on a map: Error using inpolygon (line 65) Polygon must be defined by vectors (XV, YV)

Trying to plot gridded data from .mat file onto a contour map. I have run the same exact code for two different datasets with no problem, but get the following error message when I run it for the Atlantic-East Pacific basin:
Error using inpolygon (line 65) Polygon must be defined by vectors (XV, YV).
I get about 10 other error messages in addition to the one above...the message above is the first error message.
What I want to do is take the data included in the variable Watts_Map_ATL_EPAC for all longitudes and latitudes for the first time step, which looks like this:
Watts_Map_ATL_EPAC(:,:,1)
The map and data stretch from 140W to the Prime Meridian, from 0N to 30N. The resolution is 0.25 deg x 0.25 deg, so there are 561 rows and 121 columns for the Watts_Map_ATL_EPAC data. In other words, Watts_Map_ATL_EPAC has dimensions of 561 x 121 x 306 (there are 306 timesteps).
Below is my code-any help you can provide will be great!
% filename = sample_mapping_TRMM_ATL_EPAC.m
%
% Purpose: This file incorporates clustered event power TRMM data from the
% ATL_EPAC basin and plots it on a map using filled contours, with a
% log-scaled contour bar. These plots allow for much easier spatial analysis % of the clusters, and to see how cluster size and power varies by rain rate.
%
% Author: Kevin Quinn
%
% Outside functions called:
% setMap_ATL_EPAC
% makeColorMap
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% clear workspace, data, and any open figures
clear all;
close all;
clc;
% for rain rates from 0.1 to 0.5mm/hr
for rain = 1:5;
Nrain = sprintf('%01d',rain);
% load the relevant datafiles, and cycle through files denoted by rain rate
filename = (['2004_TRMM_TROPICS_Watts_Maps_pt_' num2str(Nrain) 'mmhr_ATL_EPAC.mat']);
load(filename)
% assign lat/lon to each grid cell
gLat = 0:0.25:30; % 0N to 30N, 0.25 deg resolution
gLon = -140:0.25:0; % 140W to Prime Meridian, 0.25 deg resolution
[gLat,gLon] = meshgrid(gLat,gLon); % mesh the lat/lon grids together
% call the setMap function to create the map for the ATL_EPAC basin
setMap_ATL_EPAC
data = Watts_Map_ATL_EPAC(:,:,1); % rename cluster watts to data to make code-writing easy
contours = [10^0 10^1 10^2 10^3 10^4 10^5 10^6]; % set the contours for the colorbar
% most important step...overlay contoured cluster watts data
contourfm(gLat,gLon,log(data),log(contours));
% next two lines: place continents/land back on map
coast = load('coast');
geoshow(coast.lat,coast.long,'Color','black');
% customize the colorbar, axes, and save figure as dpng file
cb = colorbar('FontSize',12,'XTick',log(contours),'XTickLabel',contours,'Location','southoutside');%'FontSize',12,);
cMap = makeColorMap([1 1 1],[0 0 1],[1 0 0],30);
colormap(cMap);
caxis(log([contours(1) contours(length(contours))]));
set(get(cb,'XLabel'),'String','Event Power (GW)','FontSize',14,'FontWeight', ...
'bold');
t = title(['TRMM-3B42 Clusters, Rain Rate GTE 0.' num2str(Nrain) 'mm/hr, 1 May 2004']);
set(t,'FontSize',14,'FontWeight','bold');
eval(['print -dpng Sample_TRMM_Cluster_Map_pt_' num2str(Nrain) 'mmhr_ATL_EPAC.png'])
clear filename data Watts_Map_ATL_EPAC % clear out data to prevent overwriting
end
Data file: look at Watts_Map_ATL_EPAC...

Change the LineWidth in some parts of a plot

I have an ECG signal and some special points of it calculated.
I want to have thicker LineWidth between those points (each pair). I did a sample with brush.
Here are my variables,
signal % the ECG signal
t % time
Q % location of red points
T % location of yellow points
Four of these pairs are visible in picture, but there are more.
Is it possible without loop _ hold on?
You can just use hold on and plot the data again on the region of interest:
% Some dummy data
x = 0:0.01:10;
y = sin(x);
plot(x,y)
% Data that we want emphasized
% You can also select a subset of your existing data
x_start = 2;
x_end = 4;
x_thick_line = x_start:0.01:x_end;
y_thick_line = sin(x_thick_line);
% Plot over the existing plot with thicker line
hold on
plot([x_start x_end],[y_thick_line(1) y_thick_line(end)],'ro',...
x_thick_line,y_thick_line,'Color','r','LineWidth',6')
This gives the following result in Octave, should be the same in MATLAB:
You should plot that function three times (assuming a..b shall be styled differently):
0..a - standard settings
a..b - use alternate color / line_width / ...
b..end