Save Figure generated from HeatMap() from Bioinformatics Library - Matlab - matlab

I would like to save the image I generate the HeatMap() function from the bioinformatics library.
I cannot figure out to have the image without manually exporting the data.
I'd prefer to use HeatMap over Imagesc because it automatically scales the data to the mean.

I do not have the Bioinformatics Library for matlab, However you should be able to get the current figure with the function gcf. It is not the most stable way, but in most cases this will work excellent. Then you can save the figure as a figure or image with saveas.
HeatMap(...);
hFig = gcf;
saveas(hFig,'myName','png'); % You can use other image types as well and also `'fig'`
There is a second way as well. The HeatMap class also contains a plot method. This method may return the figure handle to the HeatMap plot then save the image with saveas.:
hHM = HeatMap(...);
hFig = plot(hHM);
saveas(hFig,'myName','png');

I share a part of a Matlab code that I used when I analyzed some data from TCGA
#I was considering two gene expression level taken from cancer disead tissue and
# healthy tissues comparing them with this Heatmap
labela=Gene;
labelb=Gene2;
data1=[dataN(indg,:) dataC(indg,:); dataN(indg2,:) dataC(indg2,:);];
H=HeatMap(data1,'RowLabels',
{labela,labelb},'Standardize','row','Symmetric','true','DisplayRange',2);
addTitle(H,strcat('HeatMap',project));
addXLabel(H,'patients');
addYLabel(H,'geni');
#I have allocated the plot in a variable
fig=plot(H);
# Then I saved the plot
saveas(fig,strcat('D:\Bioinformatica\Tesina...
Prova2\Risultati_lihc\',dirname,'\HM.fig'));
But if you have to run one single object I advise against waisting your time in writing code (even if it is always a good thing to explore and strengthen your knowledge), I used because each time I was running a pipeline. Otherwise you can go on
1)File ----> Export Setup
2) Export
3)Save in the format you do want!

Related

Create Matlab figures in LaTeX using matlabfrag or alternatives

I want to include Matlab figures into latex preferably with vectorised formats but with LaTeX MATLAB fonts for all text. I have been using the MATLAB function matlab2tikz which worked perfect for simple figures, but now my figures have too many data points which cause an error. So matlab2tikz is not suitable.
I've been looking at matlabfrag which I think will accomplish what I want, but when I run the script in LaTeX as detailed by the user guide it has an error File not found.
This is my code:
\documentclass{article}
\usepackage{pstool}
\begin{document}
\psfragfig{FileName}
\end{document}
Where FileName is the name of the .eps and .tex that matlabfrag creates. Has anyone come across this problem? Or recommend any other functions/methods to use?
I'm using Texmaker on Windows 7.
My advice would be to rethink your workflow.
Instead of reusing your Matlab code to plot figures and be dissappointed by ever changing outputs with matlab2tikz, start reusing your latex code to plot figures and don't bother about plotting in Matlab anymore (at least not for beautiful plots).
matlab2tikz is just generating latex code based on the latex-package pgfplots. To understand the working of this package is pretty easy, as it is intended to be similar to Matlab.
So why bother and always let matlab2tikz do the work for you? Because again and again you won't be entirely happy with the results. Just try to write the pgfplots-code from scratch and just load the data from Matlab.
Here is a convenient function I wrote to create latex-ready text files:
function output = saveData( filename, header, varargin )
in = varargin;
numCols = numel(in);
if all(cellfun(#isvector, in))
maxLength = max(cellfun(#numel, in));
output = cell2mat(cellfun(#(x) [x(:); NaN(maxLength - numel(x) + 1,1)],in,'uni',0));
fid = fopen(filename, 'w');
fprintf(fid, [repmat('%s\t',1,numCols),'\r\n'], header{:});
fclose(fid);
dlmwrite(filename,output,'-append','delimiter','\t','precision','%.6f','newline', 'pc');
else
disp('saveData: only vector inputs allowed')
end
end
Which could for example look like the following, in case of a bode diagram:
w G0_mag G0_phase GF_mag GF_phase
10.000000 40.865743 -169.818991 0.077716 -0.092491
10.309866 40.345290 -169.511901 0.082456 -0.101188
10.629333 39.825421 -169.196073 0.087474 -0.110690
10.958700 39.306171 -168.871307 0.092787 -0.121071
11.298273 38.787575 -168.537404 0.098411 -0.132411
In your tikzpicture you can then just load that file by
\pgfplotstableread[skip first n=1]{mydata.txt}\mydata
and store the table into the variable \mydata.
Now check pfgplots how to plot your data. You will find the basic plot command \addplot
\addplot table [x expr= \thisrowno{0}, y expr= \thisrowno{3} ] from \mydata;
where you directly access the columns of your text file by \thisrowno{0} (confusing, I know).
Regarding your problem with to many data points: pgfplots offers the key each nth point={ ... } to speed things up. But I'd rather filter/decimate the data already in Matlab.
The other way around is also possible, if you have to few data points the key smooth smoothes things up.

Inputting/Accessing data for GUI MATLAB

I wish to plot a simple graph of my data with sliders to change the coefficient of the y-axis data. I have created my GUI interface from quick start, with plot and sliders. I now wish to write the code (I believe in the simpleguide_OpeningFcn section) to import my data sets. My data sets are 5 different 300x1 vectors which I currently import into a a normal MATLAB file using an import function named importfile2.m.
Any help on how to get this data into the GUI for my simple plot(x,y) would be much appreciated. Cheers
An alternative would be to use setappdata and getappdata to fetch the data wherever you want from your GUI.
For example, at t he end of your importfile2.m you could use setappdata to store the data in some variable. The first argument tells MATLAB in what workspace to save it. You could, for example, use the GUI interface in itself or use the base workspace, accessible from everywhere. That's the most general way:
setappdata(0,'FancyName',YourData); %// The 0 is for the base workspace,i.e. the 'root'.
%//YourData is the actual data and 'FancyName' is whatever name you give them. It does not have to be the same name as the variable in your function. The important thing is to use the same name in getappdata as below.
If you wanted to associate the data only with the GUI figure, you would use something like this:
setappdata(handles.YourFigure_Tag,'FancyName',YourData);
To get the data in the GUI, use getappdata in its opening function (or in any callback you want) and you're good to go:
Data_inGUI = getappdata(0,'FancyName'):
A more robust way would be to store directly the data in the handles structure of the GUI, so that it's accessible from every callback:
handles.Data_inGUI = getappdata(0,'FancyName'):
guidata(hObject,handles); %// Update handles structure; important!
And that should do it. Hope that helps!
EDIT I think another solution would be to save a .mat file at the end of the import function and load it in the OpeningFcn of the GUI. Than might be simpler/faster.
EDIT 2 Following your comment below, here is what I would do:
1) In the OpeningFcn of the GUI, import the data.
[Date,OutAirTemp,SupAirtemp] = importfile3('AHU7Oct.csv')
Then you can store everything in the handles structure:
handles.Data = Date;
handles.OutAirTemp = OutAirTemp;
handles.SupAirtemp = SupAirtemp;
guidata(hObject,handles); %// Update handles structure.
Then elsewhere in the GUI (i.e. other callbacks) you can fetch the data as regular, i.e. using for example:
NewDate = handles.Date - 4 %// or whatever.
Is it a bit clearer?

How to reproduce figure through a previously saved figure handle?

I plotted the distribution of a set of data in a 3d scatter plot.
h = scatter3(D1,D2,D3,'.');
I have saved h but now need to reproduce the graph. What function should I call on h so that I can get the graph without recalculating D1, D2, D3? Because D1, D2, D3 are computationally expensive to re-calculate, I don't want to do it every time when I need a graph.
"Recreating a graph" can be done if you have the following information:
The data used to create the graph
The graph type used
Any optional settings (colors, axes, scaling, orientation, ...)
The "handle" of a graph (or figure) points to the memory where all that information is stored - but it's just a pointer. Unless you save "what is pointed to", it is no use to you. There is a very cool way to achieve this with a single command. After you have created a figure, you can simply type
saveas(gcf, 'myLastGraph.m', 'm');
Instead of gcf ("get current figure" - the handle to the most recently selected figure) you can use whatever the handle is of the graph you want to save (which must still be visible) - for example, h in your code sample. This will create two files in your current directory (if you specify a full path in the second argument, it will create the files in that directory instead):
myLastGraph.fig
myLastGraph.m
Now you can close all your graphs, clear all variables. Next, you can simply run
myLastGraph
from the command line - and your graph will be re-created, using the data that was saved on disk.
If the graph is still open, you can get the Xdata, Ydata and Zdata by using:
XYZCell=get(get(get(h,'currentaxes'),'children'),{'xdata','ydata','zdata'});
Or if you don't want a cell:
XData=get(get(get(gcf,'currentaxes'),'children'),'xdata');
YData=get(get(get(gcf,'currentaxes'),'children'),'ydata');
ZData=get(get(get(gcf,'currentaxes'),'children'),'zdata');
If the graph is closed, h is useless - as far as I'm aware there is no way to reform a graph from a closed figure handle.
Why not use save your variables first?
I1=d1;
I2=d2;
I3=d3;
scatter3(d1,d2,d3,'.');
By "computationally expensive to re-calculate" I'm not sure whether you mean calculating values of D1, D2, D3 or plotting those values. If the calculation is intensive, save the values to the workspace or save them to disk (e.g. print to a file) so you can load them again later for plotting. You can also save the graph as a *.fig file, which you can open and edit later, which might be a good choice if the plotting is the slow part.
There's no way I know of to use the handle (h) to get your data back, once you've closed the window.
With the figure window still open, however, you can use h to pull in the data:
xyzData = get(get(h, 'children'), {'xdata', 'ydata', 'zdata'});
(NB: h = scatter3(D1,D2,D3,'.'); sets h as the handle to the scattergroup. #Hugh Nolan's fine answer requires that h be the handle to the figure.)

MATLAB Saving and Loading Feature Vectors

I am trying to load feature vectors into classifiers such as a k-nearest neighbors classifier.
I have my code for GLCM, so I get contrast, correlation, energy, homogeneity in numbers (feature vectors).
My question is, how can I save every set of feature vectors from all the training images? I have seen somewhere that people had a .set file to load into classifiers (may be it is a special case for the particular classifier toolbox).
load 'mydata.set';
for example.
I suppose it does not have to be a .set file.
I'd just need a way to store all the feature vectors from all the training images in a separate file that can be loaded.
I've google,
and I found this that may be useful
but I am not entirely sure.
Thanks for your time and help in advance.
Regards.
If you arrange your feature vectors as the columns of an array called X, then just issue the command
save('some_description.mat','X');
Alternatively, if you want the save file to be readable, say in ASCII, then just use this instead:
save('some_description.txt', 'X', '-ASCII');
Later, when you want to re-use the data, just say
var = {'X'}; % <-- You can modify this if you want to load multiple variables.
load('some_description.mat', var{:});
load('some_description.txt', var{:}); % <-- Use this if you saved to .txt file.
Then the variable named 'X' will be loaded into the workspace and its columns will be the same feature vectors you computed before.
You will want to replace the some_description part of each file name above and instead use something that allows you to easily identify which data set's feature vectors are saved in the file (if you have multiple data sets). Your array of feature vectors may also be called something besides X, so you can change the name accordingly.

MATLAB query about for loop, reading in data and plotting

I am a complete novice at using matlab and am trying to work out if there is a way of optimising my code. Essentially I have data from model outputs and I need to plot them using matlab. In addition I have reference data (with 95% confidence intervals) which I plot on the same graph to get a visual idea on how close the model outputs and reference data is.
In terms of the model outputs I have several thousand files (number sequentially) which I open in a loop and plot. The problem/question I have is whether I can preprocess the data and then plot later - to save time. The issue I seem to be having when I try this is that I have a legend which either does not appear or is inaccurate.
My code (apolgies if it not elegant):
fn= xlsread(['tbobserved' '.xls']);
time= fn(:,1);
totalreference=fn(:,4);
totalreferencelowerci=fn(:,6);
totalreferenceupperci=fn(:,7);
figure
plot(time,totalrefrence,'-', time, totalreferencelowerci,'--', time, totalreferenceupperci,'--');
xlabel('Year');
ylabel('Reference incidence per 100,000 population');
title ('Total');
clickableLegend('Observed reference data', 'Totalreferencelowerci', 'Totalreferenceupperci','Location','BestOutside');
xlim([1910 1970]);
hold on
start_sim=10000;
end_sim=10005;
h = zeros (1,1000);
for i=start_sim:end_sim %is there any way of doing this earlier to save time?
a=int2str(i);
incidenceFile =strcat('result_', 'Sim', '_', a, 'I_byCal_total.xls');
est_tot=importdata(incidenceFile, '\t', 1);
cal_tot=est_tot.data;
magnitude=1;
t1=cal_tot(:,1)+1750;
totalmodel=cal_tot(:,3)+cal_tot(:,5);
h(a)=plot(t1,totalmodel);
xlim([1910 1970]);
ylim([0 500]);
hold all
clickableLegend(h(a),a,'Location','BestOutside')
end
Essentially I was hoping to have a way of reading in the data and then plot later - ie. optimise the code.
I hope you might be able to help.
Thanks.
mp
Regarding your issue concerning
I have a legend which either does not
appear or is inaccurate.
have a look at the following extracts from your code.
...
h = zeros (1,1000);
...
a=int2str(i);
...
h(a)=plot(t1,totalmodel);
...
You are using a character array as index. Instead of h(a) you should use h(i). MATLAB seems to cast the character array a to double as shown in the following example with a = 10;.
>> double(int2str(10))
ans = 49 48
Instead of h(10) the plot handle will be assigned to h([49 48]) which is not your intention.