Showing posts with label figure. Show all posts
Showing posts with label figure. Show all posts

Wednesday, April 20, 2016

Matlab Plot Latitude and Longitude with degree symbol on the axis label

Not the complete code, but it does the job.
close all
load coast
cfigure( 40, 20);
plot(long, lat, 'k')
grid on
% s = sprintf('45%c', char(176));

set(gca,'XLim',[-180 180])
set(gca,'YLim',[-180/2 180/2])
set(gca,'XTick',[-180:40: 180])
set(gca,'YTick',[-90:30: 90])

xt=get(gca,'xtick');
for k=1:numel(xt);
xt1{k}=sprintf('%d°',xt(k));
end
set(gca,'xticklabel',xt1);

xt=get(gca,'ytick');
for k=1:numel(xt);
xt1{k}=sprintf('%d°',xt(k));
end
set(gca,'yticklabel',xt1);

set(gca,'Fontsize',26)

annotation('textbox', [.15  .232 0.16  0.1 ],'EdgeColor',[ 0 0 0] )

% xlim([-180 180])
% ylim([-90 90])
hold on
plot(longitude(dayyes==0), latitude(dayyes==0), 'o', 'MarkerEdgeColor','b','MarkerSize',5);
plot(longitude(dayyes==1),latitude(dayyes==1), '*', 'MarkerEdgeColor','r','MarkerSize',6);
text(-167,-50,  sprintf('* Day Profile  ' ), 'color', 'r', 'FontSize', 26)
text(-167,-60,  sprintf('o Night Profile' ), 'color', 'b', 'FontSize', 26)
%    annotation('textbox', [-175  -55 20  15 ],'EdgeColor',[0 0 0] )
ylabel('Latitude ', 'FontSize', 26)
xlabel('Longitude ', 'FontSize', 26)
set(gcf,'Color','white')

Tuesday, March 1, 2016

Plotyy equivalent of Bar and scatter plots

It was not so easy to replace the plotyy code with the following:
The idea is simple: plot bars, hold on and then plot scatter.
The problems were axes limits and labels not alignting properly.

% Create figure
close all
figure1 = cfigure(30,10);

% Create axes
axes1 = axes('Parent',figure1, 'YTick',[0 1 2 3]);%,...

 xlim(axes1,[min(dvec_d) max(dvec_d)]);

%  Uncomment the following line to preserve the Y-limits of the axes
ylim(axes1,[0 3]);
box(axes1,'on');
hold(axes1,'on');

% Create ylabel
ylabel('PWV (cm)','FontSize',14);


% Create axes
axes2 = axes('Parent',figure1,'HitTest','off','Color','none',...
   'YTick',[0.94 0.96 0.98 1],...
    'YAxisLocation','right', 'XTick',linspace(min(dvec_d) , max(dvec_d) , 24));
 xlim(axes2,[min(dvec_d) max(dvec_d)]);
 ylim(axes2,[0.94 1]);
hold(axes2,'on');

% Create ylabel
ylabel('MOD21 \epsilon_{29}','FontSize',14);

% Create bar
 bar(dvec_d,pwv_d5,'FaceColor',[0.8 0.8 0.5],'EdgeColor',[0.5 0.99 0.9],'Parent',axes1);
 %set(axes1, 'ydir', 'reverse'); % this will put hanging bars


set(axes1,'xtick',[])
set(axes1,'xticklabel',[])
hold on
% Create scatter
scatter(dvec_d,mod21_e295d, 'Parent',axes2,'MarkerEdgeColor',[1 0 0],'Marker','*');
set(axes2,'xtick',[])
set(axes2,'xticklabel',[])
set(axes2,'xticklabel',[])

%         datetick('x','yyyy-mm' );.
datetick('x','yyyy-mm', 'keeplimits')
title(' PWV and Emissivity Time Series','FontSize',14); % add a title and define the font size
xlabel('Time ( 2003-2005)')
hold on
line( dvec_d, 1.5* ones(length(dvec_d)), 'Parent', axes1  )

set(axes2,{'ycolor'},{'r' })  
    

Wednesday, February 24, 2016

States Line disappearing in map: Solved

In matlab you can extract the states lat/lon information and plot them so that the problem of states lines disappearing can be solved.
here is an example where you can extract the state lat/lon data from the axis limit boundary and make lats/lons variables. These can be plotted with geoshow.

figure(1)
latlim = [35 45];
lonlim = [-115 -100];
    ax = worldmap(latlim, lonlim);

  states = shaperead('usastatehi','UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']);
   geoshow(ax, states, 'FaceColor', [1 1 1], 'LineWidth', 3);
   lats = [];
lons = [];
for aa = 1:length(states)
lats = horzcat(lats, states(aa).Lat);
lons = horzcat(lons, states(aa).Lon);
end
geoshow(lats,lons,'DisplayType','Line', 'Color', [0 1 0])
% latlim=[floor(min(min(SatLat))),ceil(max(max(SatLat)))];
% lonlim=[floor(min(min(SatLon))),ceil(max(max(SatLon)))];
surfacem(SatLat, SatLon, double(c66in5));
hold on
plotm( y,x ) % polygon

plotm(37 , -105 , 1, 'yo')
set(gcf,'Color','white')

Tuesday, February 2, 2016

Matlab Map plot with limits

It is not so obvious to plot matlab maps with latitude and longitude limits on the axes' ends.
The following code helped me.
figure
ax = worldmap(ylim, xlim);
states = shaperead('usastatehi','UseGeoCoords', true, 'BoundingBox', [xlim', ylim']);
geoshow(ax, states, 'FaceColor', [1 1 1]);
surfacem(LatLsatf1, LonLsatf1,NDVI1);
colormap('summer')
title(['NDVI (', DOY, ')'], 'FontSize', 20)
map2 = (colormap);
map2 = flipud(map2);
colormap(map2);
cmap = colormap; % cmap nicely puts colormap into 3 col data
% colorbar
caxis([-0  1])

setm(gca,'fontsize', 12,'PLabelLocation',[ylim(1), mean(ylim), ylim(2)],'PLineLocation',[ylim(1), mean(ylim), ylim(2)],...
    'PLabelRound',-3,'MLabelLocation',[xlim(1), mean(xlim), xlim(2)],'MLineLocation',[xlim(1), mean(xlim), xlim(2)], 'MLabelRound',-3, ...
     'Grid','on')

Thursday, September 10, 2015

Plot Clouds as white pix

Plot Clouds
figure;
c95copy = double(c95)+1;
imagesc(c95copy);
icol = colormap;
icol(64,:) = [1 1 1];
colormap(icol)

Monday, July 27, 2015

For Imagesc, plot water/nan with different color

Figure plot with the lowest value set as distinct colormap.
 figure; imagesc(Temperature)

icol =  colormap;
icol(1,:) = [0 0 0]; % or 111 for white
colormap(icol);

Wednesday, January 28, 2015

Plot LST

fn = 'MOD11_L2.A2010001.1835.041.2010006193246.hdf' Longitude = double(hdfread(fn, 'Longitude')); Latitude = double(hdfread(fn, 'Latitude')); LST = double(hdfread(fn, 'LST')); % LST550 = squeeze(LST); % this is LST .550 um LST(LST<7500 an="" lst="">65535) = NaN; LST = 0.02* LST; % fill = -9999*scale % LST550(LST550==fill)=NaN; figure load coast latlim=[floor(min(min(Latitude))),ceil(max(max(Latitude))) ]; lonlim=[floor(min(min(Longitude))),ceil(max(max(Longitude))) ]; ax = worldmap(latlim, lonlim); surfacem(Latitude, Longitude, LST); geoshow(lat, long,'Color', 'black' ) colormap; set(gcf,'Color','white') map2 = colormap; map2( 1, : ) = 1; colormap(map2); colorbar % saveas(gcf, 'plotHDF.png', 'png') close all



 figure
W(W<0) = NaN;  
load coast
latlim=[floor(min(min(Lat))),ceil(max(max(Lat))) ]; lonlim=[floor(min(min(Lon))),ceil(max(max(Lon))) ];
ax = worldmap(latlim, lonlim);
surfacem(Lat, Lon, W);
geoshow(lat, long,'Color', 'black' )
colormap; set(gcf,'Color','white')
map2 = colormap; map2( 1, : ) = 1; colormap(map2);
colorbar % saveas(gcf, 'plotHDF.png', 'png') close all
caxis([ 0 5])

Tuesday, January 13, 2015

Plotyy example #matlab #plot

A simple plotyy command for matlab to plot two data on y axis.
figure;
[ax,h1,h2] = plotyy(date,data1,date,data2);
% AX(2) = [];
set(h1,  'Markerfacecolor','k','Markersize',3)
set(h2, 'Markerfacecolor','b','Markersize',3)
% set(AX,'XAxisLocation','top', 'XTickLabel',[])
datetick('x',12,'keeplimits','keepticks')
set(ax(2),'XAxisLocation','bottom','XTickLabel',[]);
set(h1, 'Marker', 'o', 'LineStyle', 'none', 'MarkerSize', 3);
set(h2, 'Marker', '*', 'LineStyle', 'none', 'MarkerSize', 3);
title(tit);
ylabel(ax(1),'asdf(cm)') % left y-axis
ylabel(ax(2),'ttt') % right y-axis

Thursday, September 18, 2014

Map data matlab plot

Plotting Map in Matlab with the colorbar and NaNs set as transparent white.

Just call it with the lat,lon and Z (same size), and do caxis of your desire at the end. Voila!
Save it.
function hhf = mapme(Latitude, Longitude, Z)
hhf = figure
load coast
latlim=[floor(min(min(Latitude))),ceil(max(max(Latitude)))];
lonlim=[floor(min(min(Longitude))),ceil(max(max(Longitude)))];
ax = worldmap(latlim, lonlim);
pcolorm(Latitude, Longitude, Z);
geoshow(lat, long,'Color', 'black' )
colormap;
set(gcf,'Color','white')
% map2 = colormap; map2( 64, : ) = 1; colormap(map2);
colorbar

Tuesday, August 5, 2014

Map Subsection USA States using matlab

I had the regional PM2.5 map, but I wanted to have it by states. So, came up with this code which can generate state level maps. If you use it, please let me know. Current example uses the solar radiation from GCM.


Highlight one, highlight all!

There is also R version available, at:
% Create the northeast mask
% Created by NM
% August 4, 2014
%
% http://www.mathworks.com/help/map/_f7-10852.html#f7-9156
% Use shaperead to get the patch data for the boundary:
close all
% http://www.mathworks.com/help/map/understanding-raster-geodata.html#f20-12849
pcs = {'New York', 'New Jersey','Massachusetts', 'Vermont','Connecticut' ,...
     'North Carolina','Ohio','Maine', 'New Hampshire', 'Rhode Island', ...
    'Maryland', 'Delaware', 'Virginia','West Virginia','District of Columbia' };
% pcs = {     'Pennsylvania'  };

cUS = shaperead('usastatelo.shp',...
    'UseGeoCoords', true,...
    'Selector',{@(name)any(strcmpi(name,pcs),2), 'Name'});

inLat = [cUS.Lat];
inLon = [cUS.Lon];
%%
% nys = shaperead('usastatehi.shp',...
%     'UseGeoCoords', true,...
%     'Selector', {@(name)strcmpi('New York',name), 'Name'});
% inLat = nys.Lat;
% inLon = nys.Lon;

% Set the grid density to be 40 cells per degree, and use vec2mtx to rasterize the boundary and generate a referencing vector for it:
gridDensity = 100;
[inGrid, inRefVec] = vec2mtx(inLat, inLon, gridDensity);
whos

% set the limits
figure(1)
axesm eqdcyl
meshm(inGrid, inRefVec)
colormap jet(4)

[latlim, lonlim] = limitm(inGrid, inRefVec);
setm(gca, 'Flatlimit', latlim, 'FlonLimit', lonlim)
tightmap

% To fill (recode) the interior of Indiana, you need a seed point
% (which must be identified by row and column) and
% a seed value (to be allocated to all cells within the polygon).
% Select the middle row and column of the grid and choose an index value of 3
% to identify the territory when calling encodem to generate a new grid:
inPt = round([size(inGrid)/2, 3]);
inGrid3 = encodem(inGrid, inPt,1);
% redraw the map using the filled grid:
inGrid3= 1-inGrid3; % need for multiple states

meshm(inGrid3, inRefVec)


%% Now try the Data
figure(2);
udGrid = flipud(inGrid3);
imagesc(udGrid)

[m,n] = size(udGrid);


% latlim=[36 46];
%     lonlim=[-82 -69];
     [Mlat, Mlon] = ndgrid(linspace(min(inLat),max(inLat),m), linspace(min(inLon),max(inLon),n));   %Changed from 35 46, -85 -69
%     newCF = griddata(latmatf,lonmatf,flipud(data),Dlat, Dlon);
 
    figure(3)
    ax = worldmap(latlim, lonlim);
    states = shaperead('usastatehi','UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']);
%     geoshow(ax, states, 'FaceColor', [1 1 1]);
    surfacem(Mlat,Mlon,(inGrid3));
 
 
    %% Now try the data
  load('C:\Users\CREST\Copy\CCNY-14\downscale-now\Regression-2006-1.mat')

    %     newCF = griddata(latmatf,lonmatf,flipud(data),Dlat, Dlon);
figure(4)
  ax = worldmap(latlim, lonlim);
    states = shaperead('usastatehi','UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']);
    geoshow(ax, states, 'FaceColor', [1 1 0.99]);
 
    surfacem(Dlat,Dlon,isimipAve);
 
    %%
        newCF = griddata(Dlat,Dlon,isimipAve,Mlat, Mlon);
     
        inGrid3c = inGrid3;
        inGrid3c(inGrid3c<=0)= NaN;
        inGrid3c(inGrid3c>0) = 1;
        plotCF = inGrid3c.*newCF;
       
        figure(5)
     ax = worldmap(latlim, lonlim);
    states = shaperead('usastatehi','UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']);
    geoshow(ax, states, 'FaceColor', [1 1 0.99]);
 
    surfacem(Mlat,Mlon,plotCF);
 
 
%% For Penn because When added Penn, it "inverts". So adding two with nanmean
pcs = {   'New York', 'Pennsylvania',  'Massachusetts', 'Vermont','Connecticut' ,...
     'North Carolina','Ohio','Maine', 'New Hampshire', 'Rhode Island', ...
    'Maryland',  'Virginia','West Virginia','District of Columbia' };

cUS = shaperead('usastatelo.shp',...
    'UseGeoCoords', true,...
    'Selector',{@(name)any(strcmpi(name,pcs),2), 'Name'});

inLat = [cUS.Lat];
inLon = [cUS.Lon];

% nys = shaperead('usastatehi.shp',...
%     'UseGeoCoords', true,...
%     'Selector', {@(name)strcmpi('New York',name), 'Name'});
% inLat = nys.Lat;
% inLon = nys.Lon;

% Set the grid density to be 40 cells per degree, and use vec2mtx to rasterize the boundary and generate a referencing vector for it:
gridDensity = 100;
[inGrid, inRefVec] = vec2mtx(inLat, inLon, gridDensity);
whos

% set the limits
% figure(1)
% axesm eqdcyl
% meshm(inGrid, inRefVec)
% colormap jet(4)

% [latlim, lonlim] = limitm(inGrid, inRefVec);
% setm(gca, 'Flatlimit', latlim, 'FlonLimit', lonlim)
% tightmap

% To fill (recode) the interior of Indiana, you need a seed point
% (which must be identified by row and column) and
% a seed value (to be allocated to all cells within the polygon).
% Select the middle row and column of the grid and choose an index value of 3
% to identify the territory when calling encodem to generate a new grid:
inPt = round([size(inGrid)/2, 3]);
inGrid3 = encodem(inGrid, inPt,1);
% redraw the map using the filled grid:
inGrid3=   inGrid3; % need for multiple states

meshm(inGrid3, inRefVec)
%

  inGrid3c = inGrid3;
        inGrid3c(inGrid3c<=0)= NaN;
        inGrid3c(inGrid3c>0) = 1;
        plotCF2 = inGrid3c.*newCF;
  figure(6)
     ax = worldmap(latlim, lonlim);
    states = shaperead('usastatehi','UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']);
    geoshow(ax, states, 'FaceColor', [1 1 0.99]);
 
    surfacem(Mlat,Mlon,plotCF2);
 
    plotCF3d(:,:,1) = plotCF;
    plotCF3d(:,:,2) = plotCF2;
 
    iplotCF = nanmean(plotCF3d,3);
 
      figure(7)
     ax = worldmap(latlim, lonlim);
    states = shaperead('usastatehi','UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']);
    geoshow(ax, states, 'FaceColor', [1 1 0.99]);
 
    surfacem(Mlat,Mlon,iplotCF);  

Friday, May 30, 2014

Shift in the latitude in Rsig data

There was a mysterious shift in the latitude, now corrected by the following back-projection. Thanks to Todd!

latnc = ilat(:,:,1);
WGS84AxisRatioSquared = 0.9933056199957391;
latitudeWGS84Radians = latnc.*pi/180;
latitudeSphereRadians = atan( tan( latitudeWGS84Radians )  * WGS84AxisRatioSquared );
newLat =    latitudeSphereRadians *180/pi;

The Latitude projection into this Lambert Conic map seems to have some shift of about 0.2 degree (12 km resolution).
Once the Backprojection is applied, the latitude appears to align nicely.



Tuesday, November 8, 2011

Using Imagemagick shell command to crop figures

How to crop figure and save as png.
This is useful for cropping similar figures located in a folder.

Copy the code, save as cropfig.sh
and then run the cropfig.sh in your terminal...

#!/bin/bash
width=1800;
height=1680;
x_offset=502;
y_offset=40;
filelist=`ls | grep '.png'`
for image_file in $filelist
do
preextensionfilename=`convert $image_file -format "%t" info:`
convert $image_file -crop ${width}x${height}+${x_offset}+${y_offset} \
${preextensionfilename}_${width}x${height}.png
done


Wednesday, August 31, 2011

Hex code for Colormap, matlab

I wanted to set the color code for the table to match with that of the figure.

colormap(jet(33))
labels = {'0','1','2','3'};
lcolorbar(labels,'fontweight','bold')
map2 = colormap; map2( 1, : ) = 1; colormap(map2)
cmap = colormap; % cmap nicely puts colormap into 3 col data

perCmap= (single(round(cmap.*255))); % convert to 255 scale
% You can use one of these options:
colorcell = ['rgb(' num2str(perCmap(1,1)), ',', num2str(perCmap(1,2)), ',', num2str(perCmap(1,3)) ')']

colorcell = ['#' (dec2hex(perCmap(1,1))), dec2hex(perCmap(1,2)), dec2hex(perCmap(1,3)) ]
% the second worked best for me

% I then set it to fid1 for txt file, which I was writing.
<td style="color:#ffffff" bgcolor="%s">
% where %s was the string set as colorcell for open fid fprintf(fid1,'<h1>%s <td/h1>', htmlH1);


Monday, May 23, 2011

Saving Big Matlab Figure with Subplots

MATLAB Advanced GUI DevelopmentSaving Big Figure with Subplots can sometimes be tricky as the titles can be messy and the screen resolution might not help.

Here is what fixed my full-screen plot/image without destroying the titles.

fneps=[Figname,'.eps'];
set(gcf,'PaperPositionMode','auto')
print('-depsc2','-r200',fneps);
The format could be eps or png or fig... as preferred.

Friday, May 20, 2011

Making pretty Figures in Matlab

I had a function calling these with gca option.
h = figure;
%plot

set(h,'LineWidth',1.12);
x_label = 'Class';
y_label = 'Range';
fig_title = char(DATAVAR);
% DATAVAR = variables{j}; from the loop and string list created as a cell structure.
% variables = {'Var1', 'Var2'} etc.
fig_title = regexprep(fig_title, '_', ' ');% To remove the underscores

xlabel(x_label, 'FontSize',[16], 'FontWeight' ,'bold');
ylabel(y_label, 'FontSize',[16], 'FontWeight' ,'bold');
newTitle = [fig_title]; % get the title from File Name (fn)
title(newTitle, 'FontSize',[20], 'FontWeight' ,'bold' );
set(gca,'LineWidth',[2.0], 'FontSize',[14],'FontWeight','bold')

Monday, May 9, 2011

Saving Matlab Figures as EPS

Saving files as eps is slightly troublesome.

One could use various options. However, for my case, there was cropping in saveas option.

% Print to ps file
Figname = 'TestFigure'
fneps=[Figname,'.eps'];
set(gcf,'PaperPositionMode','auto')
print('-depsc2','-r200',fneps);
% print('-dpsc2','-zbuffer','-r200',fneps);
% saveas(gca,Figname,'psc2');

Wednesday, November 25, 2009

Matlab script for figure with background color

This is the Matlab script to make a white circle with dark background.

The figure1 creates a figure with dark background as indicated by the color attribute.
patch is a built in function which creates a light patch (which is a circle).

I tried the built in function "whitebg" which did not work except that it created another color background (viz: whitebg('green') gives me green background without solving the problem).
set(subplot(2,2,1),'Color','Red') actually sets the color for the subplot but I could not make it work for single figure.
Listed in Matlab file exchange:
http://www.mathworks.com/matlabcentral/fileexchange/25935
Here is the code:

The file gives a circle of given radius with dark background.
generate x and y vectors for circle.

figure1 = figure('Color',[0 0 0]);

axes1 = axes('Parent',figure1,'PlotBoxAspectRatio',...
[1 1 1],'Color',[0 0 0]);
% box('on');
patch(x,y,[1,1,1])
axis square


Note that the point here is not to generate shape, it can be done with conversion into polar co-ordinates (x,y) into (r,theta). My aim was to have different background for figure.