How to remove axis in MATLAB - matlab

axis off Not working.
function displayResults(filename,hObject, eventdata, handles)
% Open 'filename' file... for reading...
fid = fopen(filename);
for N=6:1:10
imagename = fgetl(fid);
if ~ischar(imagename), break, end % Meaning: End of File...
[x,map]=imread(imagename);
rgb=ind2rgb(x,map);
ax = handles.(sprintf('axes%d', N));
axis off;
image(rgb, 'Parent', ax);
end
guidata(hObject,handles)
Above code results in following output:
I've highlighted axis in above figure.
All images I've used is bitmap with bit depth of 8. I don't want those axis, how can I remove that?

insert the following at the end of each loop:
set(ax, 'Visible','off')
or you can do this once for all axes in the figure:
set(findobj(gcf, 'type','axes'), 'Visible','off')

Related

Print ONLY plot on MATLAB GUI

How can I print ONLY the plot created by my MATLAB GUI into a PDF document?
I know about the function available online called export_fig, but we are not allowed to make use of externally coded tools for this.
I currently have the following
function PrintButton_Callback(hObject, eventdata, handles)
set(gcf,'PaperType','A4','PaperOrientation','landscape','PaperPositionMode','auto');
print(get(handles.Axes,'Parent'), '-dpdf','Results.pdf');
However, this results in my entire GUI figure being saved.
How can I select ONLY the plot made by my axes ("Axes")?
The print command only accepts a figure as handle parameter ...
To print specified axis only a trick is to copy this axis to a new temporary figure using copyobj and use print command on the new figure.
Here is some sample code:
%% -- Test code
function [] = TestPrint()
%[
% Create figure with two axes
fig = figure(1); clf;
ax1 = subplot(1,2,1);
plot(rand(1, 12));
ax2 = subplot(1,2,2);
plot(rand(1, 12));
% Print the whole figure
print(fig, '-dpdf', 'figure.pdf');
% Print ONLY second axis
printAxis(ax2, '-dpdf', 'axis.pdf');
%]
end
%% --- Print specified axis only
% NB: Accept same arguments as 'print' except for first one which now is an axis.
function [] = printAxis(ax, varargin)
%[
% Create a temporary figure
visibility = 'on'; % You can set it to off if you want
tempFigure = figure('Visible', visibility);
cuo = onCleanup(#()clearTempFigure(tempFigure)); % Just to be sure to destroy the figure
% Copy selected axis to the temporary figure
newAx = copyobj(ax, tempFigure);
% Make it fill whole figure space
set(newAx, 'OuterPosition', [0 0 1 1]);
% Print temporary figure
print(tempFigure, varargin{1:end});
%]
end
function [] = clearTempFigure(h)
%[
if (ishandle(h)), delete(h); end
%]
end
Disable axes visibility: set(gca,'Visible','off') before printing.

MATLAB Figure Visible Off

I'm trying to save .jpg files from MATLAB, but I don't want to have the figure pop up every time since this really slows down the process. However, setting 'visible' to 'off' doesn't seem to work. What can I do to get the Figure window to not pop up?
nFrames = 2557; % Number of frames. Number of days between 1/1/2008 and 1/31/2014
for k = 183:nFrames % 183 (7/1/2008) to the number of days. Data before this is either missing or from HI
% Map of conterminous US
ax = figure(1);
set(ax, 'visible', 'off', 'units','normalized','outerposition',[0 0 1 1]) % Make window that shows up full sized, which makes saved figure clearer
ax = usamap('conus');
states = shaperead('usastatelo', 'UseGeoCoords', true,...
'Selector',...
{#(name) ~any(strcmp(name,{'Alaska','Hawaii'})), 'Name'});
faceColors = makesymbolspec('Polygon',...
{'INDEX', [1 numel(states)], 'FaceColor', 'none'}); % NOTE - colors are random
geoshow(ax, states, 'DisplayType', 'polygon', ...
'SymbolSpec', faceColors)
framem off; gridm off; mlabel off; plabel off
hold on
% Plot data
scatterm(ax,str2double(Lat_PM25{k}), str2double(Lon_PM25{k}), 40, str2double(data_PM25{k}), 'filled'); % Plot a dot at each Lat and Lon with black outline around each dot (helps show dots that are too low for it to be colored by the color bar
% Draw outline around dot with 'MarkerEdgeColor', [0.5 0.5 0.5] for gray
hold on
% Colorbar
caxis([5 30]);
h = colorbar;
ylabel(h,'ug/m3');
% Title
% date = datenum(2007, 04, 29) + k; % Convert t into serial numbers.
title(['PM2.5 24-hr Block Average Concentration ', datestr(cell2mat(date_PM25(k)), 'mmm dd yyyy')]); % Title changes every day;
% Capture the frame
mov(k) = getframe(gcf);
% Set size of paper
set(gcf,'Units','points')
set(gcf,'PaperUnits','points')
size = get(gcf,'Position');
size = size(3:4);
set(gcf,'PaperSize',size)
set(gcf,'PaperPosition',[0,0,size(1),size(2)])
% Save as jpg (just specify other format as necessary) - Must set 'facecolor' to 'none' or else color of states turn out black
eval(['print -djpeg map_US_' datestr(cell2mat(date_PM25(k)),'yyyy_mm_dd') '_PM25_24hrBlkAvg.jpg']);
clf
end
The problem is with getframe. A detailed answer was given in this thread and in this discussion.
In short you need to avoid getframe and instead do something like the following:
ax = figure(1);
set(ax, 'visible', 'off')
set(ax, 'PaperPositionMode','auto')
aviobj = avifile('file.avi');
....
for k=1:N
%# all the plotting you did before the getframe
img = hardcopy(ax, '-dzbuffer', '-r0');
aviobj = addframe(aviobj, im2frame(img));
end
aviobj = close(aviobj);

Import figures to MATLAB GUI using handles?

How can I literally take these figures and place them in the axes windows of my GUI?
I am not sure where to place handles in my user-defined code in the example below. I have 4 figures in total which look similar to this example. I want the 4 figures to be displayed in my GUI window and not in separate windows, so i've created 4 axes windows in the .fig file.
The code for this particular figure draws a grid of 66 black and white rectangles based on whether or not a value in MyVariable is a 1 or a 0. Black if MyVariable is a 1, White if MyVariable is 0. I have a file for my .fig GUI, one file to control the GUI and one with user-defined code that links to the GUI.
function test = MyScript(handles)
lots of code in between
% Initialize and clear plot window
figure(2); clf;
% Plot the west wall array panels depending on whether or not they are
% shaded or unshaded
for x = 1:11
for y = 1:6
if (MyVariable(x,y) == 1)
rectangle('position', [x-1, y-1, 1, 1] ,'EdgeColor', 'w', 'facecolor', 'k')
else if(MyVariable(x,y) == 0)
rectangle('position', [x-1, y-1, 1, 1], 'facecolor', 'w')
end
end
end
end
title('West Wall Array',...
'FontWeight','bold')
axis off
The figure for the above code looks like this:
The function definition contains all of my script code for all 4 plots because I didn't partition my script into individual functions earlier on.
My GUI script code contains:
MyScript(handles);
As DMR sais, it's necesary to set the 'CurrentAxes'. For example, if you want to plot into the axis with the tag name 'axis1' you should simply add:
axes(handles.axes1);
to your code. Below is a very simple example for a figure containing a 'axis1' and 'axis2' using your code (corrected) code from above. Im not really shure wether you want to plot on an axis on your gui itself or a separate figure. I hope I covered both cases.
function varargout = Test(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #Test_OpeningFcn, ...
'gui_OutputFcn', #Test_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before Test is made visible.
function Test_OpeningFcn(hObject, eventdata, handles, varargin)
% Choose default command line output for Test
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
plot(handles.axes2,-2*pi:0.1:2*pi,sin(-2*pi:0.1:2*pi));
% Initialize and clear plot window
MyVariable = ones(11,6);
MyVariable(1:5,1) = 0;
axes(handles.axes1);
for x = 1:11
for y = 1:6
if (MyVariable(x,y) == 1)
rectangle('position', [x-1, y-1, 1, 1] ,'EdgeColor', 'w', 'facecolor', 'k');
elseif(MyVariable(x,y) == 0)
rectangle('position', [x-1, y-1, 1, 1], 'facecolor', 'w');
end
end
end
title('West Wall Array',...
'FontWeight','bold')
figure(2); clf;
for x = 1:11
for y = 1:6
if (MyVariable(x,y) == 1)
rectangle('position', [x-1, y-1, 1, 1] ,'EdgeColor', 'w', 'facecolor', 'k');
elseif(MyVariable(x,y) == 0)
rectangle('position', [x-1, y-1, 1, 1], 'facecolor', 'w');
end
end
end
title('West Wall Array',...
'FontWeight','bold')
function varargout = Test_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
Your guide GUI should look like this:
And your result like this:
You can set the axis to plot into prior each plot command by setting the 'CurrentAxes' property of the figure.
Within GUIDE, you can tag a given axis, for example: http://www.mathworks.com/help/matlab/creating_guis/gui-with-multiple-axes-guide.html . Then within your drawing code, indicate which axis should be plotted into via the 'set' function and 'CurrentAxes' property.
A simple example is below, though it doesn't use GUIDE, only basic subplot axis handles:
% plots in most recent axis by default (ax2)
fig = figure;
ax1 = subplot(1,2,1);
ax2 = subplot(1,2,2);
plot(rand(1,10));
% indicate that you want to plot in ax1 instead
fig = figure;
ax1 = subplot(1,2,1);
ax2 = subplot(1,2,2);
set(gcf, 'CurrentAxes', ax1);
plot(rand(1,10));

Handling multiple plots in MATLAB

I am using plot(X) whereX is an n-by-k matrix, which produces k plots with n points.
How do I show the legend for this plot? More importantly, is there an easy way to show checkboxes to show or not show certain plots?
I think you can find this section of Documentation useful.
GUI that Displays and Graphs Tabular Data
http://www.mathworks.com/help/techdoc/creating_guis/bropmbk-1.html
Please use this body for plot_callback function in tableplot.m file to get a dirty implementation of the flexible legend.
function plot_callback(hObject, eventdata, column)
% hObject Handle to Plot menu
% eventdata Not used
% column Number of column to plot or clear
colors = {'b','m','r'}; % Use consistent color for lines
colnames = get(htable, 'ColumnName');
colname = colnames{column};
lgidx = get(haxes, 'UserData');
if isempty(lgidx)
lgidx = false(size(colnames));
end
if get(hObject, 'Value')
% Turn off the advisory text; it never comes back
set(hprompt, 'Visible', 'off')
% Obtain the data for that column
ydata = get(htable, 'Data');
set(haxes, 'NextPlot', 'Add')
% Draw the line plot for column
hplot = plot(haxes, ydata(:,column),...
'DisplayName', colname,...
'Color', colors{column});
lgidx(column) = true;
else % Adding a line to the plot
% Find the lineseries object and delete it
hplot = findobj(haxes, 'DisplayName', colname);
lgidx(column) = false;
delete(hplot);
end
if any(lgidx)
legend(haxes, colnames{lgidx} );
else
legend(haxes, 'off')
end
set(haxes, 'UserData', lgidx);
end
An example:
x = cumsum(rand(100,3)-0.5); %# three series with 100 points each
h = plot(x);
legend(h, {'first' 'second' 'third'})

Producing subplots and then combine them into a figure later in MATLAB

My program produces small figures during the command cycle. Is there a way to just save these figures and then combine them in one figure later?
Consider the code:
hFig = figure;
%# create temporary subplots as template
for i=1:2, h(i) = subplot(2,1,i); end %# create subplots
pos = get(h, 'Position'); %# record their positions
delete(h) %# delete them
%# load the .fig files inside the new figure
fileNames = {'a.fig' 'b.fig'}; %# saved *.fig file names
for i=1:2
%# load fig
hFigFile = hgload( fileNames{i} );
%# move/copy axis from old fig to new fig
hAx = get(hFigFile, 'Child'); %# hAx = gca;
set(hAx, 'Parent',hFig)
%#hAx = copyobj(hAx,hFig);
%# resize it to match subplot position
set(hAx, 'Position',pos{i});
%# delete old fig
delete(hFigFile)
end
This was adapted from this newsgroup discussion
Use saveas. Save your subplot as a FIG file so you have complete control over it later (as opposed to a JPG).
Choose a tiling pattern and then use subplot to display multiple figures in one.
I have an answer here as an example:
h1 = figure(1)
plot(1:10,'o-r');
title('title');
xlabel('xlabel');
ylabel('ylabel');
% Copy contents
ch(1) = copyobj(gca,gcf);
% Figure 2
h2 = figure(2)
plot(1:30,'o-r');
title('title fig2');
xlabel('xlabel');
ylabel('ylabel');
% copy contents
ch(2) = copyobj(gca,gcf);
figure(3)
sh = subplot(1,2,1);
clear axes
p = get(sh,'position');
ah = copyobj(ch(1),gcf);
set(ah,'position',p);
% Create axis template
sh = subplot(1,2,2);
clear axes
p = get(sh,'position');
ah = copyobj(ch(2),gcf);
set(ah,'position',p);
% Delete template
% delete(sh);
Amro's solution works greatly, but with boxplots you have to reset the Xtick and Xtick labels, otherwise, for some reason, they will not be resized according to the the subplot. When you create the boxplot or after opening the figure add:
set(gca,'XTick',<1d vector>,'XTickLabel',<1d cell vector>)
or put automatic ticks and labels
set(gca,'XTickMode','auto','XTickLabelMode','auto')