Labeling a string on x-axis vertically in MatLab - matlab

The following variables are used:
SP: a known 196x1 row Vector containing random numbers.
YP: a known 196x1 row Vector containing random numbers.
Names: a known 196x1 a column string containing 196 names.
The issue is within the x-axis. The array of Names in reality contain from "Jan 2000 Feb, 2000, March 2000,..., Dec 2016." Since I cannot simulate these 196 months here, I just created 196 names with a "for" function in the my code (please see the coding section).
Problem: My output from the MatLab only takes the first nine values of Names string. I want all 196 data in Names string to be posted vertically on the x-axis.
This is my output from the MatLab (See x-axis):
This is how I want my output to look like:
Here is my code:
%define variables
SP = rand(196,1)/100;
YP = (rand(196,1)/100)*2;
%plotting two vectors of SP and YP
plot(YP,'DisplayName','YP');
hold on;
plot(SP,'DisplayName','SP');
hold off;
title('SP and YP monthly returns');
%This is x-axis with creating a string of 196x1 dimensions
xlabel('Monthly time series');
for i=1:196
Names(i,:)='Sample Text'
end
set(gca, 'xTickLabels', Names);
%y-axis
ylabel('Percentage of prices discounts');
set(gca, 'yTickLabels', num2str(100.*get(gca,'yTick')','%g%%'));

when data is plotted you have only 11 xtick in x-axis so when you change their names it's normal you have 11 xtick so you can check below code
%define variables
SP = rand(196,1)/100;
YP = (rand(196,1)/100)*2;
%plotting two vectors of SP and YP
plot(YP,'DisplayName','YP');
hold on;
plot(SP,'DisplayName','SP');
hold off;
title('SP and YP monthly returns');
%This is x-axis with creating a string of 196x1 dimensions
xlabel('Monthly time series');
xTicks=1:5:196; % EDITED
% number of xticklabel control by xticks variable
set(gca,'xTick',xTicks); % EDITED
for i=1:196
Names(i,:)='Sample Text';
end
set(gca, 'xTickLabels', Names);
rotateXLabels(gca,90); %for using this command you must download it or if %
%your matlab version is 2015 or higher you have this
%function in your toolbox
output for 1:5:196 is like below picture

Related

Matlab - plotting function with a for loop over a matrix

I have an assignment which sounds like:
"“Grades per assignment”: A plot with the assignments on the x-axis and the grades on the y-axis. The x-axis must show all assignments from 1 to M, and the y-axis must show all grade −3 to 12. The plot must contain:
Each of the given grades marked by a dot. You must add a small random number (between -0.1 and 0.1) to the x- and y-coordinates of each dot, to be able tell apart the different dots which otherwise would be on top of each other when more than one student has received the same grade in the same assignment.
The average grade of each of the assignments plotted as a line"
For now i have created this function:
function gradesPlot(grades)
figure(2);
n_assignments=size(grades,2);
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.
n_assignments2=([1:size(grades,2)]);
scatter(n_assignments2,grades(:,i)'jitter', 'on', 'jitterAmount', 0.1)
hold off; % Set the hold state to off.
end
%Titles to the plot
title('Grades per assignment');
xlabel('Assignment');
ylabel('Given grades');
break;
end
when i run the code it says that the vectors must be same length.
And it looks like it doesn't loop over the matrix more than ones.
The test grades i am using as input is looking like this:
grades=[[-3,4,10];[7,4,12];[7,10,12];[0,4,4];[2,2,2];[2,2,2]]
I hope some of you guys can help me get this function to work - maybe in an easier way?
Thank you in advance
You should not turn off hold since it is tells MatLab to plot everything in the current active plot, roughly speaking. You can find a possible solution to your problem down below: I added some explanations in comments.
function gradesPlot(grades)
figure(2);
% Extract the relevant information: number of assignements, number of grades
[n_assignments,n_grades] = size(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
% For Scatter, you have to provide 2 vectors of the same size: in this
% way, we are putting al the dots corresponding to the grades of the
% i-th assignement in correspondence of the i-th coordinate on the x
% axis. We are also temporary saving in h the handle to the attributes
% of the dots, in order to retrieve the color.
h = scatter(i*ones(n_grades,1),grades(i,:),'jitter', 'on', 'jitterAmount', 0.1);
% This plots the horizontal line corresponding to the average of the
% grades related to the i-th assignement
l = line([i-0.5 i+0.5],[1,1]*mean(grades(i,2:end)));
% For using the same color as the dots.
l.Color = h.CData;
end
%Titles to the plot
title('Grades per assignment');
xlabel('Assignment');
ylabel('Given grades');
axis([0 n_assignments+1 -4 13])
end
Remember that the break command must be used inside a loop, not for exiting a function. Use return if you desire.

Plotting Eye Diagram from ADS Data in 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)')

How to set xticklables to certain places in the graph in matlab

I have two vectors that contain the average temperatures of two cities. I am plotting those vectors to a graph. I have 398 temperatures in both vectors so my xticklables are naturally from 1 to 398. I am trying to change my xticklables so they would show the month and the year like this: 01/2017. however I seem to be unable to write anything to my xtick. Here is my code for xtickmodification:
ax.XTick=[1,32,62,93,124,154,185,215,246,277,305,336,366,397];
ax.XTicklabels={'05/2014','06/2014','07/2014','08/2014','09/2014',
'10/2014','11/2014','12/2014','01/2015','02/2015','03/2015','04/2015','05/2015','06/2015'};
ax.XTick contains the vector element that starts a new month. So how can i get the ax.XTicklabels-line to my graph?
use XTickLabel property instead of XTicklabels. in addition, you can set XTickLabelRotation property if the labels are long strings:
x = rand(398,1);
h = plot(x);
ax = gca;
ax.XTick=[1,32,62,93,124,154,185,215,246,277,305,336,366,397];
ax.XTickLabel={'05/2014','06/2014','07/2014','08/2014','09/2014',...
'10/2014','11/2014','12/2014','01/2015','02/2015','03/2015','04/2015','05/2015','06/2015'};
ax.XTickLabelRotation = 45;
Have you tried the following
set(gca, 'xtick', ax.XTick);
set(gca, 'xticklabels', ax.XTicklabels);

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 Plotting a monthly data on a daily axis

I have a plot that has 528 points on the x-axis. The x-axis is labelled by mmm yyyy. I want to plot data over it, but the data is in monthly form. I want to take each of the monthly data points and plot it at the beginning of the month as a dot.
% Axis and plot
t = 731:1258; % 20120101 to 20130611
y = reshape(dataPoint_Anom1x1(:,:,731:end),[],1); % Size 528x1
x = datenum(2009, 12, 31) + t; % Convert t into serial numbers
plot(x, y); % Plot data
hold on
The part below is what I'm having trouble with. The dataPoint_Clim1x1 is size 12x1. (1,1) corresponds to January, (2,1) corresponds to February, etc. I need to plot the corresponding month's climatology point as a dot at the beginning of each month between January 2012 and June 2013.
%%%% Plot climatology on the same graph
dataClim_1x1 = dataClim(u,v,:); % Array that only contains points 1 degree away from 72.5E and 67.25S
B = mean(dataClim_1x1); % Average along the column
dataPoint_Clim1x1 = mean(B,2); % Average along the row
x_dataClim = ???
y_dataClim = reshape(dataPoint_Clim1x1, [],1); % Change dataPoint_Clim1x1 into a 1 column matrix
plot(x_dataClim,y_dataClim) % y_dataClim is only 12x1.
So the plot command right above is wrong. Do I just need to somehow set up the x-axis so that it plots every month with datenum somehow? I don't want to use a secondary axis though.
I think you just need to define your x coordinates of the points with
x_dataClim = datenum(2011, 1:12, 1);
This generates "the first of the month":
>> datestr(x_dataClim)
ans =
01-Jan-2011
01-Feb-2011
01-Mar-2011
01-Apr-2011
01-May-2011
01-Jun-2011
01-Jul-2011
01-Aug-2011
01-Sep-2011
01-Oct-2011
01-Nov-2011
01-Dec-2011
The cool thing is that you can actually "go into next year" - so
>> datestr(datenum(2011, 11:14, 1))
ans =
01-Nov-2011
01-Dec-2011
01-Jan-2012
01-Feb-2012
Here's what I ended up doing:
x = datenum(2011,1:30,1); % 30 months of data (2 and 1/2 years)
y_dataClim = reshape(dataPoint_Clim1x1, [],1); % Change dataPoint_Clim1x1 into a 1 column matrix
y = cat(1, y_dataClim, y_dataClim, y_dataClim(1:6,:));
scatter(x,y, 50,'fill'); % Plot scatter plot