MATLAB Plotting a monthly data on a daily axis - matlab

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

Related

Plotting a set of data with time in hh:mm format in x axis in matlab

I have a code which goes like this:
clc;clear;close all
%%
Time=linspace(16.8,17.8,230400)';
Field=linspace(50,145,230400)';
figure('units','normalized','outerposition',[0 0 1 1])
plot(Time,Field)
%%
figure('units','normalized','outerposition',[0 0 1 1])
hammng_wndw_size=4096;
window=hamming(hammng_wndw_size); %window size
noverlap=512; % the noverlaps its the no. of points for repeating the window
nfft=4096; %size of fft
fs=32; %sampling freq
[Sp,F,T,P]=spectrogram(Field,window,noverlap,nfft,fs,'yaxis');
T_forspectrogrm=T./3600+Time(1);
surf(T_forspectrogrm,F,10*log10(P),'edgecolor','none','FaceColor','interp');
axis tight;ylim([0 4]);view(0,90);
colormap(jet);colorbar;
The result of this plot is these two figures:
The xaxis is time and y axis is some other quantity, lets say field. Now, when I plotting, the x axis starts from 16.8 to 17.8 for first figure and 16.8 and 18.8 for second figure. This actually corresponds to 16:48:00 to 17:48:00 and similarly for the second one. How do I have to modify the program to convert the x-axis into hh:mm format do this job?
I tried in this fashion
TimeInReqFrmat=datestr(Time(:,1),'HH:MM:SS'), but this gives me a string of characters.
I am using Matlab 2016a.
Thanks in advance
You approach was almost right. You need to use datetimes. It's just a bit tricky to convert decimal numbers to date times
x = [16.8;17.8]
H = floor(x); % hour
m = floor((x-H)*60); % minute
S = (x-H)*60-m; % second
% create date vector
DateVec = datetime(0,0,0,H,m,S);
plot(DateVec,rand(size(DateVec)))
% set the tick format
xtickformat('HH:mm')
There are many options to set the xtickformat.
If you have unix-time, you can convert it right away
datetime(x,'ConvertFrom','datenum')
If you have just time, you will need to come up with a date for a proper datetime. Otherwiese you can also think of using duration.

In Matlab, how to draw lines from the curve to specific xaxis position?

I have a spectral data (1000 variables on xaxis, and peak intensities as y) and a list of peaks of interest at various specific x locations (a matrix called Peak) which I obtained from a function I made. Here, I would like to draw a line from the maximum value of each peaks to the xaxis - or, eventually, place a vertical arrow above each peaks but I read it is quite troublesome, so just a vertical line is welcome. However, using the following code, I get "Error using line Value must be a vector of numeric type". Any thoughts?
X = spectra;
[Peak,intensity]=PeakDetection(X);
nrow = length(Peak);
Peak2=Peak; % to put inside the real xaxis value
plot(xaxis,X);
hold on
for i = 1 : nbrow
Peak2(:,i) = round(xaxis(:,i)); % to get the real xaxis value and round it
xline = Peak2(:,i);
line('XData',xline,'YData',X,'Color','red','LineWidth',2);
end
hold off
Simple annotation:
Here is a simple way to annotate the peaks:
plot(x,y,x_peak,y_peak+0.1,'v','MarkerFaceColor','r');
where x and y is your data, and x_peak and y_peak is the coordinates of the peaks you want to annotate. The add of 0.1 is just for a better placing of the annotation and should be calibrated for your data.
For example (with some arbitrary data):
x = 1:1000;
y = sin(0.01*x).*cos(0.05*x);
[y_peak,x_peak] = PeakDetection(y); % this is just a sketch based on your code...
plot(x,y,x_peak,y_peak+0.1,'v','MarkerFaceColor','r');
the result:
Line annotation:
This is just a little bit more complicated because we need 4 values for each line. Again, assuming x_peak and y_peak as before:
plot(x,y);
hold on
ax = gca;
ymin = ax.YLim(1);
plot([x_peak;x_peak],[ymin*ones(1,numel(y_peak));y_peak],'r')
% you could write instead:
% line([x_peak;x_peak],[ymin*ones(1,numel(y_peak));y_peak],'Color','r')
% but I prefer the PLOT function.
hold off
and the result:
Arrow annotation:
If you really want those arrows, then you need to first convert the peak location to the normalized figure units. Here how to do that:
plot(x,y);
ylim([-1.5 1.5]) % only for a better look of the arrows
peaks = [x_peak.' y_peak.'];
ax = gca;
% This prat converts the axis unites to the figure normalized unites
% AX is a handle to the figure
% PEAKS is a n-by-2 matrix, where the first column is the x values and the
% second is the y values
pos = ax.Position;
% NORMPEAKS is a matrix in the same size of PEAKS, but with all the values
% converted to normalized units
normpx = pos(3)*((peaks(:,1)-ax.XLim(1))./range(ax.XLim))+ pos(1);
normpy = pos(4)*((peaks(:,2)-ax.YLim(1))./range(ax.YLim))+ pos(2);
normpeaks = [normpx normpy];
for k = 1:size(normpeaks,1)
annotation('arrow',[normpeaks(k,1) normpeaks(k,1)],...
[normpeaks(k,2)+0.1 normpeaks(k,2)],...
'Color','red','LineWidth',2)
end
and the result:

Create and Plot Time Series Data in Matlab

I have a (1x700) vector x for which I would like to create and plot a time series object in Matlab. Each observation corresponds to one month, and the first observation belongs to January 1960. I tried the following:
state1 = timeseries(x,1:size(x,2));
state1.Name = 'Test';
state1.TimeInfo.Units = 'months';
state1.TimeInfo.StartDate = 'Jan-1960'; % Set start date.
state1.TimeInfo.Format = 'yy'; % Set format for display on x-axis.
state1.Time = state1.time - state1.time(1); % Express time relative to the start date.
plot(state1);
However, I still see numbers on the x-axis instead of years. Could anyone please help? Thanks in advance!
Create random data. 1/12 corresponds to the fraction of a year that each month represents.
x = 1960:1/12:1970;
y = rand(1,121);
Then plot the x and y axes data using plot.
plot( x, y )
Then set the tick as follows for a decade per year. 1960:1970 will generate [1960 1961 ...] each corresponding to the tick's year.
set( gca, 'XTick', 1960:1970 );
Here is the output plot.
Doing 1 year intervals get VERY MESSY with lots of data. So solutions include doing a larger interval or setting your ticks to display vertically instead of horizontally. This code below shows how to set 5 year intervals instead.
set( gca, 'XTick', 1960:5:2010 );

Merge two (or more) time stamped data and plot showing the gap(s)

what is the best way to merge and plot 2 (or more) time stamped data so that the plot includes the gaps between the known data?
For example, I have a cell with time and heart rate values for Monday, and another for Friday. I would like to plot all data from Mon to Friday which includesthe gaps showing nothing was recorded from Tues-Thurs?
So far if I merge the data
data = [mon;fri]
% get the time serial numbers
dateInd = 1;
dateString = data(dateIndex);
dateFormat = 'dd/mm/yyyy HH:MM:SS';
tNum = datenum(dateString{1},dateFormat);
t = linspace(tNum(1),tNum(end),length(tNum));
% get heart rates,
HRIndex = 2;
HR = data(HRIndex);
and plot
plot(t,HR)
datetick('x','ddd');
I obviously get Monday and Fridays data merged into a single plot 2 days long. but I would like to have a plot 5 days long with data only showing on monday and Friday. What is the best way to achieve this?
I hope this makes sense,
Many thanks,
Jon
To achieve such effect I usually fill missing data with NaNs, like here:
x = linspace(0,2*pi,100);
y = sin(x);
y(20:30) = NaN; % there will be a gap from point#20 to point#30
plot(x,y);
The reason is that MatLab does not draw plot points where either x or y data are NaNs.
In your case you may add missing time points to your time data (to have corect gap) and NaNs to corresponding Y-values.
By the way, why don't you plot two separate plots with X-data of the second one properly shifted?
EDIT
Case 1: your x-data is time relative to the start of the day (in 0-24 interval). If you plot them directly they will overlap. You have to add some offset manually, like this:
% generate test data
x1 = linspace(0,1,25); % 25 points per first day
y1 = rand(25,1);
x2 = linspace(0,1,25); % 25 points per second day
y2 = rand(25,1);
% plot them as two separate plots
% so line style, color, markers may be set separately
XOffset = 3;
figure;
plot(x1,y1,'*k-', x2+XOffset,y2,'*r-');
% plot them as single separate plot
% so line style, color, markers are the same
figure;
plot([x1(:); NaN; x2(:)+XOffset],[y1(:); NaN; y2(:)],'*k-');
% One NaN is enough to insert a gap.
Case 2: your x-data have full time information including the date (like MatLab's serial date number, see help on now function, for example). Then just plot them, they will be offset automatically.
% generate test data
XOffset = 3;
x1 = linspace(0,1,25); % 25 points per first day
y1 = rand(25,1);
x2 = linspace(0,1,25)+XOffset; % 25 points per second day, with offset
y2 = rand(25,1);
% plot them as two separate plots
% so line style, color, markers may be set separately
figure;
plot(x1,y1,'*k-', x2,y2,'*r-');
% plot them as single separate plot
% so line style, color, markers are the same
figure;
plot([x1(:); NaN; x2(:)],[y1(:); NaN; y2(:)],'*k-');
% One NaN is enough to insert a gap.
Also instead of
plot(x1,y1,'*k-', x2,y2,'*r-');
you may do like this (number of plots is not limited):
hold on;
plot(x1,y1,'*k-');
plot(x2,y2,'*r-');
hold off;

MATLAB - Pixelize a plot and make it into a heatmap

I have a matrix with x and y coordinates as well as the temperature values for each of my data points. When I plot this in a scatter plot, some of the data points will obscure others and therefore, the plot will not give a true representation of how the temperature varies in my data set.
To fix this, I would like to decrease the resolution of my graph and create pixels which represent the average temperature for all data points within the area of the pixel. Another way to think about the problem that I need to put a grid over the current plot and average the values within each segment of the grid.
I have found this thread - Generate a heatmap in MatPlotLib using a scatter data set - which shows how to use python to achieve the end result that I want. However, my current code is in MATLAB and even though I have tried different suggestions such as heatmap, contourf and imagesc, I can't get the result I want.
You can "reduce the resolution" of your data using accumarray, where you specify which output "bin" each point should go in and specify that you wish to take a mean over all points in that bin.
Some example data:
% make points that overlap a lot
n = 10000
% NOTE: your points do not need to be sorted.
% I only sorted so we can visually see if the code worked,
% see the below plot
Xs = sort(rand(n, 1));
Ys = rand(n, 1);
temps = sort(rand(n, 1));
% plot
colormap("hot")
scatter(Xs, Ys, 8, temps)
(I only sorted by Xs and temps in order to get the stripy pattern above so that we can visually verify if the "reduced resolution" worked)
Now, suppose I want to decrease the resolution of my data by getting just one point per 0.05 units in the X and Y direction, being the average of all points in that square (so since my X and Y go from 0 to 1, I'll get 20*20 points total).
% group into bins of 0.05
binsize = 0.05;
% create the bins
xbins = 0:binsize:1;
ybins = 0:binsize:1;
I use histc to work out which bin each X and Y is in (note - in this case since the bins are regular I could also do idxx = floor((Xs - xbins(1))/binsize) + 1)
% work out which bin each X and Y is in (idxx, idxy)
[nx, idxx] = histc(Xs, xbins);
[ny, idxy] = histc(Ys, ybins);
Then I use accumarray to do a mean of temps within each bin:
% calculate mean in each direction
out = accumarray([idxy idxx], temps', [], #mean);
(Note - this means that the point in temps(i) belongs to the "pixel" (of our output matrix) at row idxy(1) column idxx(1). I did [idxy idxx] as opposed to [idxx idxy] so that the resulting matrix has Y == rows and X == columns))
You can plot like this:
% PLOT
imagesc(xbins, ybins, out)
set(gca, 'YDir', 'normal') % flip Y axis back to normal
Or as a scatter plot like this (I plot each point in the midpoint of the 'pixel', and drew the original data points on too for comparison):
xx = xbins(1:(end - 1)) + binsize/2;
yy = ybins(1:(end - 1)) + binsize/2;
[xx, yy] = meshgrid(xx, yy);
scatter(Xs, Ys, 2, temps);
hold on;
scatter(xx(:), yy(:), 20, out(:));