Bad contour lines when plotting gridded data - matlab

I have heavily edited data from an underwater glider that measures temperature, conductivity, and pressure. From that we get salinity, density and sigma (sigma = density - 1000). The instrument did not sample very well, hence the heavy editing. I need to make "pretty" contour plots for a poster. This is not for a publication so I am not worried about the amount of filtering or smoothing.
I am having trouble with the contour lines of sigma (density), please see below.
The black contour lines should trace the filled contours of sigma but they look very bad. The data was binned by 1 m before any gridding is done. here is the code used to generate the plots.
Here is the code used to generate this image
% load data
load Matlab_data
maxy = 50;
t = 1;
Tstep = t./24./60; % Grid data on t minute time intervals
X1 = time(1)-Tstep:Tstep:time(end)+Tstep;
Y1 = 0:1:maxy; % Grid data on 1 meter depth intervals
ygrid = [' Depth grid: ' num2str(diff(Y1(1:2)))];
xgrid = [' Time grid: ' num2str(diff(X1(1:2)))];
[X,Y]= meshgrid(X1,Y1);
bad_vals = isnan(sal) .* ~isfinite(sal) .* isnan(press); % don't include NaNs or funky imaginary salinities in the contours
vals = find(bad_vals == 0);
Zd = griddata(time(vals),depth(vals),density(vals),X,Y);
Zt = griddata(time(vals),depth(vals),temp(vals),X,Y);
Zs = griddata(time(vals),depth(vals),sal(vals),X,Y);
Zst = griddata(time(vals),depth(vals),sigmat(vals),X,Y);
% Interpolate over gaps
vst = interp1gap(sigmat);
vs = interp1gap(sal);
% Grid interpolated salinity and sigma data
Zst_interp = griddata(time(vals),depth(vals),vst(vals),X,Y);
Zs_interp = griddata(time(vals),depth(vals),vs(vals),X,Y);
%% Contour Plot
% Set up the figure
figure3=figure('Position', [2000, 50, 1500, 500]);
clf
colormap(jet);
% Temperature
ax1 = subplot(2, 1,1);
[c,h] = contourf(X,Y,Zst,50,'linestyle','none'); %,[4:.5:9],'linestyle','none');
cRange = caxis;
hold on
[c2,h2] = contour(X,Y,Zst,[24 24.5 25],'color','k'); %,[22:.5:26.5],'linewidth',1.5,'color','k');
clabel(c2,h2,'fontsize',10,'labelspacing',150);
set(h2,'linewidth',1)
hc = colorbar;
colormap(jet);
datetick('x','mm/dd','keeplimits','keepticks');
grid on;
box on
pos = get(gca,'position');
set(gca,'YDir','reverse')%,'position',[pos(1) pos(2) pos(3)-.06 pos(4)]);
set(gca,'xlim',[time(1)+.5./24 time(end)-.5./24],...
'ylim',[0 maxy],'fontsize',8,'xminortick','on','yminortick','on');
set(get(hc,'ylabel'),'string','Sigma-Theta (kg m^-^3)','rotation',270,'verticalalignment','bottom');
ylabel('Ocean Depth (m)');
xlabel('Date');
%title(['Sigma Theta (kg m^-^3) -' strrep(tag,'_','\_')], 'fontweight', 'bold','FontSize',12)
title(['Sigma Theta (kg m^-^3) :' ygrid xgrid ], 'fontweight', 'bold','FontSize',12)
ax2 = subplot(2, 1,2);
%h=pcolor(X,Y,Zst);
[c,h] = contourf(X,Y,Zst_interp,50,'linestyle','none'); %,[4:.5:9],'linestyle','none');
shading interp
hc = colorbar;
cRange = caxis;
hold on
[c2,h2] = contour(X,Y,Zst_interp,[24 24.5 25],'color','k'); %,[22:.5:26.5],'linewidth',1.5,'color','k');
clabel(c2,h2,'fontsize',10,'labelspacing',150);
set(h2,'linewidth',1)
hc = colorbar;
colormap(jet);
caxis(cRange);
datetick('x','mm/dd','keeplimits','keepticks');
grid on;
box on
pos = get(gca,'position');
set(gca,'YDir','reverse')%,'position',[pos(1) pos(2) pos(3)-.06 pos(4)]);
set(gca,'xlim',[time(1)+.5./24 time(end)-.5./24],...
'ylim',[0 maxy],'fontsize',8,'xminortick','on','yminortick','on');
set(get(hc,'ylabel'),'string','Sigma-Theta (kg m^-^3)','rotation',270,'verticalalignment','bottom');
ylabel('Ocean Depth (m)');
xlabel('Date');
% title(['Sigma Theta (kg m^-^3) -' strrep(tag,'_','\_')], 'fontweight', 'bold','FontSize',12)
title(['Sigma Theta interp1gap (kg m^-^3) :' ygrid xgrid ], 'fontweight', 'bold','FontSize',12)
Please help! I have TWO issues... the first and most obvious is the ugly black contour lines, these should "flow" around the filled contours nicely. If anyone has experience or suggestions of how to smooth these please pass it along, with code if possible.
The second issue lies in the bottom plot, I need to fill the gaps in data (due to editing original bad data). I used the function interp1gap, available on the File exchange but it also interpolates the data to deeper depths, which I do not want. I just want the gaps to be filled in, such as by choosing their horizontal neighbors and filling in.
Please let me know if you have any suggestions for fixing this! I have attached the data (Matlab_data.mat) and it includes time, depth, sal (salinity), sigmat, press, temp, and density.
Is this an issue of gridding? Please be as specific as possible and any code and figures would be greatly appreciated if you have time to look into this.
The data is available drop box https://www.dropbox.com/s/mjd8f9bzdvwddk5/Matlab_data.mat?dl=0
Thank you very much in advance!

Related

Does anybody know how should I use animatedline in order to draw me an orbit immediately?

This is the main code
%%%%%%%%%%%% Valori pentru Rcsc
%%%%Pozitiile si vitezele pe cele 3 axe
y0(1,1)= 743322.3616 ;
y0(2,1)= -6346021.219 ;
y0(3,1)= -3394131.349 ;
y0(4,1)= 5142.38067;
y0(5,1)= 4487.44895 ;
y0(6,1)= -7264.00872;
%%%% Timpul
tspan=[0 :864];
%%%% Masa(kg) si aria suprafetei satelitului (m^2)
m = 217 ; %320;
A = 1.2; %8;
%%%% Metoda Runge-Kutta de ordin 4
h=1;
y = zeros(6, tspan(end)/h);
y(:,1) = y0;
for i=1:(tspan(end)/h)
H=sqrt(y(1,i)^2+y(2,i)^2+y(3,i)^2);
k_1 = proiectia(tspan(i), y(:,i), H, m, A, y(4:6, i));
k1=double(k_1);
k_2 = proiectia(tspan(i)+0.5*h, y(:,i)+0.5*h*k_1, H, m, A, y(4:6, i));
k2=double(k_2);
k_3 = proiectia((tspan(i)+0.5*h), (y(:,i)+0.5*h*k_2), H, m, A, y(4:6, i));
k3=double(k_3);
k_4 = proiectia((tspan(i)+h),(y(:,i)+k_3*h), H, m, A, y(4:6, i));
k4=double(k_4);
y(:,i+1) = double(y(:,i) + (1/6)*(k1+2*k2+2*k3+k4)*h);
end
%%% Distanta satelitului
Rcsc = ((y(1,:).^2 + y(2,:).^2 + y(3,:).^2).^0.5);
n=50;
%plot(tspan,Rcsc)
%% Textured 3D Earth example
%
% Ryan Gray
% 8 Sep 2004
% Revised 9 March 2006, 31 Jan 2006, 16 Oct 2013
%% Options
space_color = 'k';
npanels = 180; % Number of globe panels around the equator deg/panel = 360/npanels
alpha = 1; % globe transparency level, 1 = opaque, through 0 = invisible
GMST0 = []; % Don't set up rotatable globe (ECEF)
%GMST0 = 4.89496121282306; % Set up a rotatable globe at J2000.0
% Earth texture image
% Anything imread() will handle, but needs to be a 2:1 unprojected globe
% image.
image_file = 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/cd/Land_ocean_ice_2048.jpg/1024px-Land_ocean_ice_2048.jpg';
% Mean spherical earth
erad = 6371008.7714; % equatorial radius (meters)
prad = 6371008.7714; % polar radius (meters)
erot = 7.2921158553e-5; % earth rotation rate (radians/sec)
%% Create figure
figure('Color', space_color);
hold on;
orbit=animatedline;
addpoints(orbit,y(1,:),y(2,:),y(3,:));
drawnow
% Turn off the normal axes
set(gca, 'NextPlot','add', 'Visible','off');
axis equal;
axis auto;
% Set initial view
view(0,30);
axis vis3d;
%% Create wireframe globe
% Create a 3D meshgrid of the sphere points using the ellipsoid function
[x, y, z] = ellipsoid(0, 0, 0, erad, erad, prad, npanels);
globe = surf(x, y, -z, 'FaceColor', 'none', 'EdgeColor', 0.5*[1 1 1]);
%% Texturemap the globe
% Load Earth image for texture map
cdata = imread(image_file);
% Set image as color data (cdata) property, and set face color to indicate
% a texturemap, which Matlab expects to be in cdata. Turn off the mesh edges.
set(globe, 'FaceColor', 'texturemap', 'CData', cdata, 'FaceAlpha', alpha, 'EdgeColor', 'none');
What I wanna do is that when I run the script a figure with the Earth should appear, and while the positions are being caluclated by the runge kutta algorithm it should upload the orbit in real time. But now the figure appears only after the Rk algorithm is being calculated till the end of tspan and the orbit from the figure is already uploaded without intermediate points. What should I do? I've seen on github that others use animatedline and drawnow.
I was thinking about
orbit=animatedline;
addpoints(orbit,y(1,:),y(2,:),y(3,:));
drawnow
end
But where should I put this line exactly? if I put it in the rk loop it doesn't work and if I put it
% Create figure
figure('Color', space_color);
%%
orbit=animatedline;
addpoints(orbit,y(1,:),y(2,:),y(3,:));
drawnow
it first displays a figure with the orbit but not by intermediate points and then a different figure with the Earth ,while the orbit and the Earth should be in the same figure.
You are using animatedline in a wrong way.
The line:
orbit = animatedline;
should be placed before the loop that calculates the points, and the lines:
addpoints(orbit,y(1,i),y(2,i),y(3,i));
drawnow
should be placed within it, to add one (or several) points to the line on each iteration. But, a better approach, would be to first calculate all the orbit and then use a loop for the animation. This way you have more control over the rate of the animation. Here is a small example using your case:
orbit = animatedline;
for k = 1:size(y,2)
addpoints(orbit,y(1,k),y(2,k),y(3,k));
drawnow
end
Alternative option
Don't use animated line just keep updating the data in the plot. Here is a simple workout for this:
% create a sphere with earth map on it:
set(gcf,'Color','k')
earth = imread('earth.jpg');
[X,Y,Z] = sphere(50);
warp(-X,Y,-Z,earth)
axis off
view(-46,17)
% set an animation of a simple orbit:
Nframes = 100; % number of steps in the orbit
% calculation of the orbit:
orb = linspace(-pi,pi,Nframes);
x = cos(orb).*1.5;
y = sin(orb);
hold on
% plot the whole orbit invisible, just for setting the axes limits:
tmp = plot(x,y,'Color','none');
p = plot(x(1),y(1),'LineWidth',3,'Color','m'); % plot the first step
hold off
for k = 1:numel(orb)
p.XData = x(1:k); % update the data of the plot
p.YData = y(1:k);
pause(0.05) % delay
end
The result:

Speed up coloring segments of a spline curve?

I am trying to color segments of a spline curve with different RGB values. Many thanks to #Suever, I have a working version:
x = [0.16;0.15;0.25;0.48;0.67];
y = [0.77;0.55;0.39;0.22;0.21];
spcv = cscvn([x, y].'); % spline curve
N = size(x, 1);
figure;
hold on;
for idx = 1:N-2
before = get(gca, 'children'); % before plotting this segment
fnplt(spcv, spcv.breaks([idx, idx+1]), 2);
after = get(gca, 'children'); % after plotting this segment
new = setdiff(after, before);
set(new, 'Color', [idx/N, 1-idx/N, 0, idx/N]); % set new segment to a specific RGBA color
end
hold off;
Now I am looking to speed it up. Is it possible?
No explicit benchmarks per se, but you can vectorise this easily by
a. collecting the plotted points and dividing them into 'segments' (e.g. using the buffer function)
b. setting the 'color' property of the Children (thanks to #Suever for pointing out this can be done on an array of object handles directly)
%% Get spline curve
x = [0.16; 0.15; 0.25; 0.48; 0.67];
y = [0.77; 0.55; 0.39; 0.22; 0.21];
spcv = cscvn ([x, y].');
%% Split into segments
pts = fnplt (spcv); xpts = pts(1,:).'; ypts = pts(2,:).';
idx = buffer ([1 : length(xpts)]', 10, 1, 'nodelay'); % 10pt segments
lastidx=idx(:,end); lastidx(lastidx==0)=[]; idx(:,end)=[]; % correct last segment
% Plot segments
plot (xpts(idx), ypts(idx), xpts(lastidx), ypts(lastidx), 'linewidth', 10);
% Adjust colour and transparency
Children = flipud (get (gca, 'children'));
Colours = hsv (size (Children, 1)); % generate from colourmap
Alphas = linspace (0, 1, length (Children)).'; % for example
set (Children, {'color'}, num2cell([Colours, Alphas],2));
Note: As also pointed out in the comments section (thanks #Dev-iL), setting the colour to an RGBA quadruplet the way you ask (i.e. as opposed to a simple RGB triplet) is a newer (also, for now, undocumented) Matlab feature. This code, e.g. will not work in 2013b.

Computing the surface between two lines

I have the following figure, where I plotted two surfaces and I wanted to indicate the intersection of both of them. To do that, I did the following:
zdiff = z1-z2;
C = contours(x,y,zdiff,[0 0]);
xL = C(1, 2:end);
yL = C(2, 2:end);
zL = interp2(x, y, z1, xL, yL);
line(xL, yL, zL, 'Color', 'k', 'LineWidth', 2,'Linestyle','--'); hold on;
line(xL, yL, zeros(size(zL)), 'Color', 'k', 'LineWidth', 2); hold off;
Now, I want to plot the vertical surface between the actual intersection (dash line) and its projection over XY (solid line), but I cannot figure out how to do that. Any ideas?
Another really simple option:
dist = (diff(xL).^2+diff(yL).^2).^0.5; %distance between x,y
cdist = [0, cumsum(dist)]; %cumsum of the distance
area = trapz(cdist,zL); %The area
Why not calculating it manually?
Something like (untested):
Area = 0
for i=1:numel(xL)-1
base = sqrt( (xL(i)-xL(i+1))^2 + (yL(i)-yL(i+1))^2);
Area =Area + base * (zL(i) + zL(i+1))/2;
end;
maybe not pretty but its a oneliner it might do the trick. maybe you have to adjust the format as this code is for (1,N) vectors
xL=(1:100); %size 1 100
yL=(1:100) ;%size 1 100
zL=rand(1,100);%size 1 100
line(xL,yL,zL)
line(xL,yL,zeros(size(zL)))
hold on
surf(repmat(xL,100,1),repmat(yL,100,1),cell2mat(arrayfun(#(x,y) linspace(x,y,100)',zL,zeros(size(zL)),'UniformOutput',false)))
xL=sin((1:30)/10); % Data generation for test only. Use your data
yL=cos((1:30)/10); % Data generation for test only. Use your data
zL=2+xL.*yL; % Data generation for test only. Use your data
surf([xL;xL],[yL;yL],[zeros(size(zL));zL]); % plot the surface

Zoom region within a plot in Matlab

I'm using Matlab to produce figures, and I'm wondering if there is a way to plot a zoomed region in a figure of the overall data?
I have scatter data plotted over one week, with the x-axis in hours, and I want to zoom into the first 3 hours, and display them within the main figure with the x-axis label of minutes.
The plotting code I have so far is as follows:
allvalsx = marabint(:,2)
allvalsy = marabint(:,5)
subvalsx = marabint(1:7,2);
subvalsy = marabint(1:7,2);
%% Plots the scatter chart.
sizemarker = 135
handle = scatter(allvalsx, allvalsy, sizemarker, '.')
figure(1)
axes('Position',[.2 .2 .2 .2])
handle2 = scatter(subvalsx, subvalsy, '.r')
title(plotTitle)
xlabel('Time since treatment (hours)')
ylabel('Contact angle (deg)')
% Axis scales x1, x2, y1, y2
axis([0, marabint(length(marabint),2) + 10, 0, 120]);
% This adds a red horizontal line indicating the untreated angle of the
% sample.
untreatedLine = line('XData', [0 marabint(length(marabint),2) + 10], 'YData', [untreatedAngle untreatedAngle], 'LineStyle', '-', ...
'LineWidth', 1, 'Color','r');
% Adding a legend to the graph
legendInfo = horzcat('Untreated angle of ', untreatedString)
hleg1 = legend(untreatedLine, legendInfo);
% This encases the plot in a box
a = gca;
% set box property to off and remove background color
set(a,'box','off','color','none')
% create new, empty axes with box but without ticks
b = axes('Position',get(a,'Position'),'box','on','xtick',[],'ytick',[]);
% set original axes as active
axes(a)
% link axes in case of zooming
linkaxes([a b])
set(gcf,'PaperUnits','inches');
set(gcf,'PaperSize', [8.267 5.25]);
set(gcf,'PaperPosition',[0 0.2625 8.267 4.75]);
set(gcf,'PaperPositionMode','Manual');
set(handle,'Marker','.');
print(gcf, '-dpdf', '-r150', horzcat('markertest4.pdf'));
This produces the following
Can anyone help me out with this?
yeah, I think I know what you need. Try this:
zoomStart = 0;
zoomStop = 3;
set(gca, 'XLim', [zoomStart zoomStop])
Let me know if that doesn't do what you need, and I'll give you a different way.

Drawing the major and minor axis of an elliptical object in MATLAB

This program currently inputs an image of a coin, thresholds it, binarizes it, and finds the major and minor axis lengths of the segmented elliptical using the regionprops function. How do I output a subplot where I draw the axes used to calculate the 'MajorAxisLength' and 'MinorAxisLength' over the original image?
I have appended my code for your perusal.
% Read in the image.
folder = 'C:\Documents and Settings\user\My Documents\MATLAB\Work';
baseFileName = 'coin2.jpg';
fullFileName = fullfile(folder, baseFileName);
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
%Alert user.
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
% Get the dimensions of the image. numberOfColorBands should be = 3.
[rows columns numberOfColorBands] = size(rgbImage);
% Display the original color image.
subplot(2, 3, 1);
imshow(rgbImage, []);
title('Original color Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'Position', get(0,'Screensize'));
% Extract the individual red color channel.
redChannel = rgbImage(:, :, 1);
% Display the red channel image.
subplot(2, 3, 2);
imshow(redChannel, []);
title('Red Channel Image', 'FontSize', fontSize);
% Binarize it
binaryImage = redChannel < 100;
% Display the image.
subplot(2, 3, 3);
imshow(binaryImage, []);
title('Thresholded Image', 'FontSize', fontSize);
binaryImage = imfill(binaryImage, 'holes');
labeledImage = bwlabel(binaryImage);
area_measurements = regionprops(labeledImage,'Area');
allAreas = [area_measurements.Area];
biggestBlobIndex = find(allAreas == max(allAreas));
keeperBlobsImage = ismember(labeledImage, biggestBlobIndex);
measurements = regionprops(keeperBlobsImage,'MajorAxisLength','MinorAxisLength')
% Display the original color image with outline.
subplot(2, 3, 4);
imshow(rgbImage);
hold on;
title('Original Color Image with Outline', 'FontSize',fontSize);
boundaries = bwboundaries(keeperBlobsImage);
blobBoundary = boundaries{1};
plot(blobBoundary(:,2), blobBoundary(:,1), 'g-', 'LineWidth', 1);
hold off;
I had the same task as you for some project I did 2 years ago. I've modified the code I used then for you below. It involved calculating the covariance matrix for the datapoints and finding their eigenvalues/eigenvectors. Note here that because of circular symmetry, the minor and major axis will be somewhat "random". Also note that I have made the image binary in a very naïve way to keep the code simple.
% Load data and make bw
clear all;close all; clc;
set(0,'Defaultfigurewindowstyle','docked')
I = imread('american_eagle_gold_coin.jpg');
Ibw = im2bw(I,0.95);
Ibw = not(Ibw);
figure(1);clf
imagesc(Ibw);colormap(gray)
%% Calculate axis and draw
[M N] = size(Ibw);
[X Y] = meshgrid(1:N,1:M);
%Mass and mass center
m = sum(sum(Ibw));
x0 = sum(sum(Ibw.*X))/m;
y0 = sum(sum(Ibw.*Y))/m;
%Covariance matrix elements
Mxx = sum(sum((X-x0).^2.*Ibw))/m;
Myy = sum(sum((Y-y0).^2.*Ibw))/m;
Mxy = sum(sum((Y-y0).*(X-x0).*Ibw))/m;
MM = [Mxx Mxy; Mxy Myy];
[U S V] = svd(MM);
W = V(:,1)/sign(V(1,1)); %Extremal directions (normalized to have first coordinate positive)
H = V(:,2);
W = 2*sqrt(S(1,1))*W; %Scaling of extremal directions to give ellipsis half axis
H = 2*sqrt(S(2,2))*H;
figure(1)
hold on
plot(x0,y0,'r*');
quiver(x0,y0,W(1),H(1),'r')
quiver(x0,y0,W(2),H(2),'r')
hold off
Look at the documentation for the Orientation attribute that regionprops() can return to you.
This gives the angle between the positive x-axis and the major axis of the ellipse. You should be able to derive the equation for the major axis line in terms of that angle, and then just make a grid of x-axis points, and compute the major axis line's value for all the points in your grid, then just plot it like you would plot any other curve in MATLAB.
To do the same for the minor axis, just note that it will be 90 degrees further counter-clockwise from the major axis, then repeat the step above.
Usually one does it with computing eigenvectors, as explained in the Wikipedia article Image moment under 'examples'. That would be the correct way.
But I wonder, if you know the centroid and the boundingbox from MATLAB, then the endpoint of the major axis must be in the upper left or upper right corner. So checking (apart from noise) these two corners, if there are pixel, would give you the major axis. The minor axis then is just orthogonal to it with respect to the centroid.
Sorry for not having MATLAB code ready.
The reasoning is not that wrong, but not so good either, using the orientation as written above is better ;)