Print ONLY plot on MATLAB GUI - matlab

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.

Related

Imagesc ButtonDownFcn problems in MATLAB, using custom toolbar action

I'm trying to use the ButtonDownFcn on an imagesc figure in MATLAB. I want to enable this function by clicking on a custom button I have created on the toolbar.
The ButtonDownFcn will call methods that will cause it to return the position of the pixel selected using the ButtonDownFcn, so that I can graph how that pixel changes through time.
NOTES:
- I am using GUIDE in matlab
- imagesc is plotting a 3D matrix. I already have implemented code that allows me to travel through how the image changes through time, using a button created in GUIDE.
What I am struggling with, at the moment, is the ButtonDownFcn of the imagesc. I've read over and over on how to do this (through research on the internet), but I can't seem to get it to work.
Any help is appreciated.
Here is my code:
% --------------------------------------------------------------------
function ui_throughTime_ClickedCallback(hObject, eventdata, handles)
% hObject handle to ui_throughTime (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
valS = get(handles.txt_zaxis,'string');
display(valS);
val = str2num(valS);
d = handles.data;
m = imagesc(d(:,:,val),'parent',handles.axis, 'HitTest', 'off','buttondownfcn',{#getPlace, handles});
set(handles.axis,'buttondownfcn',{#getPlace, handles,m});
function getPlace(hObject,handles,event_obj,place)
% data = randn(120,160);
% ax = axes;
% imagesc(data,);
if (gcf == place)
pause(1);
cursor = get(handles.axis,'CurrentPoint'); % get point
% Get X and Y from point last clicked on the axes
x = (cursor(1,1));
y = (cursor(1,2));
disp(['x = ' num2str(x) ' y = ' num2str(y)]);
end
Here is a simple example:
%% Init
fig_h = figure('CloseRequestFcn', 'run = 0; delete(fig_h);');
rgb = imread('peppers.png');
run = 1; t = 0;
%% Loop
while run
t = t + 0.05;
imagesc(rgb*sin(t), 'ButtonDownFcn', 'disp(''Clicked'')');
pause(0.01);
end
Above the 'ButtonDownFcn' of the image is being used so the 'HitTest' property of the image must be 'On'.
Below is the case that the 'ButtonDownFcn' of the axes are used and since the image is in front of the axes, 'HitTest' property of the image should be 'Off' or the axes won't be selectable.
%% Loop
ax = axes;
while run
t = t + 0.05;
imagesc(rgb*sin(t), 'Parent', ax, 'HitTest', 'Off');
set(ax, 'ButtonDownFcn', 'disp(''Clicked'')')
pause(0.01);
end
It's also possible to use the figure 'ButtonDownFcn' and again the image 'HitTest' should be 'Off'. However in this case clicked points of outside of the image ( or interested area) should be filtered programmatically.
Hope it helps.

Clear all graphical object of a certain type

I created a GUI program with MATLAB, with a menu bar and tabs, each containing a plot, a text box, etc. The problem is that when I select a tab from the menu bar and plot something, the axes objects from former plots don't disappear.
I tried to use cla reset unsuccessfully. clf worked, but my menu bar disappeared as well.
Here is my code:
function fel1_Callback(hObject, eventdata, handles) %% plot sin(x)
cla reset
clc
clear all
d = inputdlg('n:','Ertekadas',1);
n = str2double(d);
x=linspace(-3*pi,3*pi,1000);
y=sin(x);
plot(x,y,'k','LineWidth',4)
sz='ymcrgbkymcrgbkymcrgbkymcrgbk';
hold on
title('Sin(x) Taylor sora')
%n = str2num(N);
f=zeros(size(x));
for i=1:n
t=(-1)^(i-1)*x.^(2*i-1)/factorial(2*i-1);
f=f+t;
plot(x,f,sz(i),'LineWidth',2)
axis([-10 10 -10 10])
pause(0.1)
hold on
n=n+1;
end
function fel7_Callback(hObject, eventdata, handles) %%Sum 1/n^2
clear all
clc
cla reset
title('Suma 1/n^2','fontsize',20)
d = inputdlg('Epszilon:','Ertek',1);
epsz = str2double(d);
n=1;
x=0;
while 1/n^2>epsz
x=x+sum(1/n^2);
n=n+1;
end
A = uicontrol('style','text','units','pixels',...
'position',[550 550 120 40],'fontsize',20,'string','Epsz =');
B = uicontrol('style','text','units','pixels',...
'position',[670 550 120 40],'fontsize',20);
set(B,'String',epsz)
C = uicontrol('style','text','units','pixels', ...
'position',[550 400 120 40],'fontsize',20,'string','Osszeg =');
D = uicontrol('style','text','units','pixels',...
'position',[670 400 120 40],'fontsize',20);
set(D,'String',x)
I use only one main GUI figure. My menu bar contains a lot of plots and calculations, not only these two.
The problem is that hold on prevents anything from being erased and just keeps adding to the plot. Nowhere in your code do you turn hold off. If you want to keep using the hold command, your code needs to look like this:
function fel1_Callback(hObject, eventdata, handles) %% plot sin(x)
d = inputdlg('n:','Ertekadas',1);
n = str2double(d);
x=linspace(-3*pi,3*pi,1000);
y=sin(x);
hold off % The next plot command should now clear the old plot and create a new one**
plot(x,y,'k','LineWidth',4)
sz='ymcrgbkymcrgbkymcrgbkymcrgbk';
hold on
title('Sin(x) Taylor sora')
%n = str2num(N);
f=zeros(size(x));
for i=1:n
t=(-1)^(i-1)*x.^(2*i-1)/factorial(2*i-1);
f=f+t;
plot(x,f,sz(i),'LineWidth',2)
axis([-10 10 -10 10])
pause(0.1)
%hold on %not necessary, this was turned on before the loop
n=n+1;
end
hold off % return the figure to the normal (default) "hold off" state

How to remove axis in 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')

Several graphs in 1 loop, each iteration adds a line on every figure

Trying to engineer the following in Matlab:
** loop start;
y(:,i) = function of x;
z(:,i) = function of x;
plot(x,y(:,i)) on figure 1, hold all;
plot(x,z(:,i)) on figure 2, hold all;
** loop end;
add title, legend, etc for figure 1 (NB: we have multiple lines);
add title, legend, ets for figure 2 (NB: same, have multiple lines for the legend);`
Tried multiple combinations without much luck. Managed to get 2 figures but only the 2-nd displays multiple lines, not the first. And can't figure how to add legends to these 2 correctly.
Save a handle to each figure, and to each axis object:
fh1 = figure;
hold all;
ah1 = gca;
fh2 = figure;
hold all;
ah2 = gca;
for i=1:N
y(:,i) = function of x;
z(:,i) = function of x;
plot(ah1, x, y(:,i)); %# tell it which axis to use (ah1)
plot(ah2, x, z(:,i)); %# (ah2)
end
legend(ah1, ...) %# legend options here
legend(ah2, ...) %# and the other legend
%# note: you can set figure properties for each using fh1, fh2 handles.
You can do this:
figHandle1 = figure(1);
figHandle2 = figure(2);
Then when you want to plot on that figure do this:
figure(figHandle1) %Plot on figure 1
%ie plot(someStuff)
figure(figHandle2) %Plot on figure 2
Also its the same for the title and stuff, you jjust need to identify which figure by doing:
figure(handle);
Hope this helps.

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'})