Hello
I want to represent data with 2 variables (latitude and longitude) in 2D format. The value is represented by color and the 2 variables as the 2 axis and I am using the contourf function to plot my data. All the data comes from a xlsx file and I put it in a matrix.
Locations = xlsread('Availability results.xlsx');
column_numberloc = 1; % Column in the locations file containing the number of the locations
column_latitude = 2; % Column in the locations file containing the latitude of the locations
column_longitude = 3; % Column in the locations file containing the longitude of the locations
column_availability = 4; % Column in the locations file containing the availability of the locations
min_latitude = min(Locations(:,column_latitude));
max_latitude = max(Locations(:,column_latitude));
min_longitude = min(Locations(:,column_longitude));
max_longitude = max(Locations(:,column_longitude));
max_availability = max(Locations(:,column_availability));
min_availability = min(Locations(:,column_availability));
longitude = Locations(:,column_longitude);
latitude = Locations(:,column_latitude);
Contour = zeros(23,17);
for numerofile=1:204
[coord_x,coord_y] =transformation(Locations(numerofile,column_latitude),Locations(numerofile,column_longitude));
Contour(coord_x,coord_y) = Locations(numerofile,column_availability);
end
for i=1:23
for j=1:17
if Contour(i,j) == 0
Contour(i,j) = NaN;
end
end
end
cMap=jet(256);
figure(1);
x = linspace(min_longitude,max_longitude,17);
y = linspace(min_latitude,max_latitude,23);
newpoints = 100;
[xq,yq] = meshgrid(linspace(min(x),max(x),newpoints),linspace(min(y),max(y),newpoints ));
Contourq = interp2(x,y,Contour,xq,yq,'linear',max_availability);
[c,h]=contourf(xq,yq,Contourq,100);
%[c,h]=contourf(x,y,Contour,50);
set(h, 'edgecolor','none');
colormap(cMap);
cb=colorbar;
caxis([min_availability max_availability]);
The transformation function allows me to place all the data in the Contour matrix as it associate a longitude and a latitude to a row and a column.
I've putted a NaN for every data equal to zero to have a better look at my data and I obtained this :
interpolation_linear
Which is nice but I wanted this data to be close to :
Without interpolation
So, I decided to change the linear interpolation to a 'nearest' interpolation and I got this :
interpolation_nearest
I can see more data but the contour plot isn't as smooth as with the linear interpolation.
I've seen many posts about how to make smooth contour plot (that's how I found the function 'interp2') but I think that my problem comes from the NaN data which prevent me from having a smooth contour plot at the edge between NaN values and the rest like the first image but with enough data like the third image.
My question is : Do you know how can I get a smooth edge contour plot with enough data thanks to the nearest interpolation but with a nice visual like the first image ?
Thank you very much
Since you are doing an interpolation on a square grid, you could directly display a 2D image with imagesc.
The advantage is that you can access the AlphaData property of image objects, which can be used as a display mask.
r=rand(50); % random 50x50 array
r(11:20,11:20)=NaN; % some hole filled with NaN
imagesc(r) % show the image, with NaN considered as the lowest value in color scale
imagesc(r,'AlphaData',~isnan(r)) % show the image, with NaN values set as fully transparent
You may also then:
set a display mask first
replace zeros or NaN with some meaningful values (nearest non NaN value?)
interpolate with interp2, perhaps even with the 'cubic' parameter for improved smoothness
display only the meaningful part of the image thanks to the display mask set in AlphaData.
Related
I'd like to create a heat map to analyze the porosity of some specimens that I have 3D-printed. the X-Y coordinates are fixed since they are the positions in which the specimens are printed on the platform.
Heatmap:
Tbl = readtable('Data/heatmap/above.csv');
X = Tbl(:,1);
Y = Tbl(:,2);
porosity = Tbl(:,3);
hmap_above = heatmap(Tbl, 'X', 'Y', 'ColorVariable', 'porosity');
The first question is: how can I sort the Y-axis of the plot? since it goes from the lower value (top) to the higher value (bottom) and I need it the other way around.
The second question is: I only have around 22 data points and most of the chart is without color, so I'd like to get a smoother heatmap without the black parts.
The data set is quite simple and is shown below:
X
Y
porosity
74.4615
118.3773
0.039172163
84.8570
69.4699
0.046314637
95.2526
20.5625
0.041855213
105.6482
-28.3449
0.049796110
116.0438
-77.2522
0.045010692
25.5541
107.9817
0.038562053
35.9497
59.0743
0.041553065
46.3453
10.1669
0.036152061
56.7408
-38.7404
0.060719664
67.1364
-87.6478
0.037756115
-23.3533
97.5861
0.052840845
-12.9577
48.6787
0.045216851
-2.5621
-0.2286
0.033645353
7.8335
-49.1360
0.030670865
18.2290
-98.0434
0.024952472
-72.2607
87.1905
0.036199237
-61.8651
38.2831
0.026725885
-51.4695
-10.6242
0.029212058
-41.0739
-59.5316
0.028572611
-30.6783
-108.4390
0.036796151
-121.1681
76.7949
0.031688096
-110.7725
27.8876
0.034619855
-100.3769
-21.0198
0.039070101
-89.9813
-69.9272
NaN
-79.5857
-118.8346
NaN
If you want to assign color to the "black parts" you will have to interpolate the porosity over a finer grid than you currently have.
The best tool for 2D interpolation over a uniformly sampled grid is griddata
First you have to define the X-Y grid you want to interpolate over, and choose a suitable mesh density.
% this will be the number of points over each side of the grid
gridres = 100 ;
% create a uniform vector on X, from min to max value, made of "gridres" points
xs = linspace(min(X),max(X),gridres) ;
% create a uniform vector on Y, from min to max value, made of "gridres" points
ys = linspace(min(Y),max(Y),gridres) ;
% generate 2D grid coordinates from xs and ys
[xq,yq]=meshgrid(xs,ys) ;
% now interpolate the pososity over the new grid
InterpolatedPorosity = griddata(X,Y,porosity,xq,yq) ;
% Reverse the Y axis (flip the `yq` matrix upside down)
yq = flipud(yq) ;
Now my version of matlab does not have the heatmap function, so I'll just use pcolor for display.
% now display
hmap_above = pcolor(xq,yq,InterpolatedPorosity);
hmap_above.EdgeColor = [.5 .5 .5] ; % cosmetic adjustment
colorbar
colormap jet
title(['Gridres = ' num2str(gridres)])
And here are the results with different grid resolutions (the value of the gridres variable at the beginning):
Now you could also ask MATLAB to further graphically smooth the domain by calling:
shading interp
Which in the 2 cases above would yield:
Notes: As you can see on the gridres=100, you original data are so scattered that at some point interpolating on a denser grid is not going to produce any meaningful improvment. No need to go overkill on your mesh density if you do not have enough data to start with.
Also, the pcolor function uses the matrix input in the opposite way than heatmap. If you use heatmap, you have to flip the Y matrix upside down as shown in the code. But if you end up using pcolor, then you don't need to flip the Y matrix.
The fact that I did it in the code (to show you how to do) made the result display in the wrong orientation for a display with pcolor. Simply comment the yq = flipud(yq) ; statement if you stick with pcolor.
Additionally, if you want to be able to follow the isolevels generated by the interpolation, you can use contour to add a layer of information:
Right after the code above, the lines:
hold on
contour(xq,yq,InterpolatedPorosity,20,'LineColor','k')
will yield:
I have a number of 2d probability mass functions from 2 categories. I am trying to plot the contours to visualise them (for example at their half height, but doesn't really matter).
I don't want to use contourf to plot directly because I want to control the fill colour and opacity. So I am using contourc to generate xy coordinates, and am then using fill with these xy coordinates.
The problem is that the xy coordinates from the contourc function have strange numbers in them which cause the following strange vertices to be plotted.
At first I thought it was the odd contourmatrix format, but I don't think it is this as I am only asking for one value from contourc. For example...
contourmatrix = contourc(x, y, Z, [val, val]);
h = fill(contourmatrix(1,:), contourmatrix(2,:), 'r');
Does anyone know why the contourmatrix has these odd values in them when I am only asking for one contour?
UPDATE:
My problem seems might be a failure mode of contourc when the input 2D matrix is not 'smooth'. My source data is a large set of (x,y) points. Then I create a 2D matrix with some hist2d function. But when this is noisy the problem is exaggerated...
But when I use a 2d kernel density function to result in a much smoother 2D function, the problem is lessened...
The full process is
a) I have a set of (x,y) points which form samples from a distribution
b) I convert this into a 2D pmf
c) create a contourmatrix using contourc
d) plot using fill
Your graphic glitches are because of the way you use the data from the ContourMatrix. Even if you specify only one isolevel, this can result in several distinct filled area. So the ContourMatrix may contain data for several shapes.
simple example:
isolevel = 2 ;
[X,Y,Z] = peaks ;
[C,h] = contourf(X,Y,Z,[isolevel,isolevel]);
Produces:
Note that even if you specified only one isolevel to be drawn, this will result in 2 patches (2 shapes). Each has its own definition but they are both embedded in the ContourMatrix, so you have to parse it if you want to extract each shape coordinates individually.
To prove the point, if I simply throw the full contour matrix to the patch function (the fill function will create patch objects anyway so I prefer to use the low level function when practical). I get the same glitch lines as you do:
xc = X(1,:) ;
yc = Y(:,1) ;
c = contourc(xc,yc,Z,[isolevel,isolevel]);
hold on
hp = patch(c(1,1:end),c(2,1:end),'r','LineWidth',2) ;
produces the same kind of glitches that you have:
Now if you properly extract each shape coordinates without including the definition column, you get the proper shapes. The example below is one way to extract and draw each shape for inspiration but they are many ways to do it differently. You can certainly compact the code a lot but here I detailed the operations for clarity.
The key is to read and understand how the ContourMatrix is build.
parsed = false ;
iShape = 1 ;
while ~parsed
%// get coordinates for each isolevel profile
level = c(1,1) ; %// current isolevel
nPoints = c(2,1) ; %// number of coordinate points for this shape
idx = 2:nPoints+1 ; %// prepare the column indices of this shape coordinates
xp = c(1,idx) ; %// retrieve shape x-values
yp = c(2,idx) ; %// retrieve shape y-values
hp(iShape) = patch(xp,yp,'y','FaceAlpha',0.5) ; %// generate path object and save handle for future shape control.
if size(c,2) > (nPoints+1)
%// There is another shape to draw
c(:,1:nPoints+1) = [] ; %// remove processed points from the contour matrix
iShape = iShape+1 ; %// increment shape counter
else
%// we are done => exit while loop
parsed = true ;
end
end
grid on
This will produce:
I have two 3D images, i need to register these two images using "lsqcurvefit". I know that I can use "imregister" but I want to use my own registration using "lsqcurvefit" in Matlab. My images are are following Gaussian distribution. it is not documented well that how should I provide it, anyone can help me in detail?
image registration is a repeated process of maping source image to target image using i.e affine. i want to use intensity base registration, and i use all voxels of my image. therefore, i need to fit these two images as much as possible.
Thanks
Here's an example of how to do point-wise image registration using lsqcurvefit. Basically you make a function that takes a set of points and an Affine matrix (we're just going to use the translate and rotate parts but you can use skew and magnify if desired) and returns a new set of points. There's probably a built-in function for this already but it's only two lines so it's easy to write. That function is:
function TformPts = TransformPoints(StartCoordinates, TransformMatrix)
TformPts = StartCoordinates*TransformMatrix;
Here's a script that generates some points, rotates and translates them by a random angle and vector, then uses the TransformPoints function as the input for lsqcurvefit to fit the needed transformation matrix for the registration. Then it's just a matrix multiplication to generate the registered set of points. If we did this all right the red circles (original data) will line up with the black stars (shifted then registered points) very well when the code below is run.
% 20 random points in x and y between 0 and 100
% row of ones pads out third dimension
pointsList = [100*rand(2, 20); ones(1, 20)];
rotateTheta = pi*rand(1); % add rotation, in radians
translateVector = 10*rand(1,2); % add translation, up to 10 units here
% 2D transformation matrix
% last row pads out third dimension
inputTransMatrix = [cos(rotateTheta), -sin(rotateTheta), translateVector(1);
sin(rotateTheta), cos(rotateTheta), translateVector(2);
0 0 1];
% Transform starting points by this matrix to make an array of shifted
% points.
% For point-wise registration, pointsList represents points from one image,
% shiftedPoints points from the other image
shiftedPoints = inputTransMatrix*pointsList;
% Add some random noise
% Remove this line if you want the registration to be exact
shiftedPoints = shiftedPoints + rand(size(shiftedPoints, 1), size(shiftedPoints, 2));
% Plot starting sets of points
figure(1)
plot(pointsList(1,:), pointsList(2,:), 'ro');
hold on
plot(shiftedPoints(1,:), shiftedPoints(2,:), 'bx');
hold off
% Fitting routine
% Make some initial, random guesses
initialFitTheta = pi*rand(1);
initialFitTranslate = [2, 2];
guessTransMatrix = [cos(initialFitTheta), -sin(initialFitTheta), initialFitTranslate(1);
sin(initialFitTheta), cos(initialFitTheta), initialFitTranslate(2);
0 0 1];
% fit = lsqcurvefit(#fcn, initialGuess, shiftedPoints, referencePoints)
fitTransMatrix = lsqcurvefit(#TransformPoints, guessTransMatrix, pointsList, shiftedPoints);
% Un-shift second set of points by fit values
fitShiftPoints = fitTransMatrix\shiftedPoints;
% Plot it up
figure(1)
hold on
plot(fitShiftPoints(1,:), fitShiftPoints(2,:), 'k*');
hold off
% Display start transformation and result fit
disp(inputTransMatrix)
disp(fitTransMatrix)
I have two 3D arrays, one contains the 3D data of an electric field and the other is a 3D mask of the object that I am interested in, taking the product of these two arrays gives me an array with the electric field of just the mask. I have successfully created an isosurface of the mask but when I try to make an isosurface of the product of the mask and the electric field array I get the same graph as when I plot just the mask (which is just an array of zeroes and 1's). Is there a way to represent the data on the isosurface?
For the moment I simply put my arrays in to the isosurface function:
isosurface(mask), which gives me:
I then try to plot the product of my mask and data array:
isosurface(mask.*EArr) and I get the following:
But if I look at just a single slice using the code
imagesc(mask(:,:,35).*EArr(:,:,35)) I get:
What I'm looking to do is to get view the slices of the last picture as a 3D object similar to the way that I can view my mask as a 3D object in the first picture.
If I understand well, you want to plot your field on the surface of your mask.
To do so, get the patch returned by isosurface, then intrepolate your field on vertices of this patch. Finaly, plot it using the resulting interpolated data as 'FaceVertexCData'.
Here is an example with dummy data :
% PREPARATION
% ===========
% GENERATE A GRID
[X Y Z] = meshgrid([0:1/100:1],[0:1/100:1],[0:1/100:1]);
% GENERATE RANDOM DATA
DATA = zeros(101,101,101);
DATA(:) = interp3([0:1/10:1],[0:1/10:1],[0:1/10:1],rand(11,11,11),X(:),Y(:),Z(:),'cubic');
% GENERATE A RANDOM MASK
MASK = zeros(101,101,101);
MASK(:) = sqrt(sum([X(:)-0.5 Y(:)-0.5 Z(:)-0.5].^2,2)) - 0.3 - interp3([0:1/10:1],[0:1/10:1],[0:1/10:1],0.1*rand(11,11,11),X(:),Y(:),Z(:),'cubic');
%
% ACTUAL PROBLEM
% ==============
% EXTRACT THE MASK SURFACE
SURF = isosurface(X,Y,Z,MASK,0);
% INTERPOLATE DATA ON MASK SURFACE
DATA_SURF = interp3(X,Y,Z,DATA,SURF.vertices(:,1),SURF.vertices(:,2),SURF.vertices(:,3));
% PLOT THE MASK SURFACE AND DATA
hold on; axis square; axis([0 1 0 1 0 1]); view(3); camlight
patch('Faces',SURF.faces,'Vertices',SURF.vertices,'EdgeColor','none','FaceColor','interp','FaceVertexCData',DATA_SURF);
This gives things like that :
Try using isosurface(mask,th) where th is the value where the isosurface will be created. As I dont know the magnitude of your data I can not suggest you a value. Try different values, e.g. 0.01
I'm trying to make a color plot in matlab using output data from another program. What I have are 3 vectors indicating the x-position, y-yposition (both in milliarcseconds, since this represents an image of the surroundings of a black hole), and value (which will be assigned a color) of every point in the desired image. I apparently can't use pcolor, because the values which indicate the color of each "pixel" are not in a matrix, and I don't know a way other than meshgrid to create a matrix out of the vectors, which didn't work due to the size of the vectors.
Thanks in advance for any help, I may not be able to reply immediately.
If we make no assumptions about the arrangement of the x,y coordinates (i.e. non-monotonic) and the sparsity of the data samples, the best way to get a nice image out of your vectors is to use TriScatteredInterp. Here is an example:
% samplesToGrid.m
function [vi,xi,yi] = samplesToGrid(x,y,v)
F = TriScatteredInterp(x,y,v);
[yi,xi] = ndgrid(min(y(:)):max(y(:)), min(x(:)):max(x(:)));
vi = F(xi,yi);
Here's an example of taking 500 "pixel" samples on a 100x100 grid and building a full image:
% exampleSparsePeakSamples.m
x = randi(100,[500 1]); y = randi(100,[500 1]);
v = exp(-(x-50).^2/50) .* exp(-(y-50).^2/50) + 1e-2*randn(size(x));
vi = samplesToGrid(x,y,v);
imagesc(vi); axis image
Gordon's answer will work if the coordinates are integer-valued, but the image will be spare.
You can assign your values to a matrix based on the x and y coordinates and then use imagesc (or a similar function).
% Assuming the X and Y coords start at 1
max_x = max(Xcoords);
max_y = max(Ycoords);
data = nan(max_y, max_x); % Note the order of y and x
indexes = sub2ind(size(data), max_y, max_x);
data(indexes) = Values;
imagesc(data); % note that NaN values will be colored with the minimum colormap value