Coding

Adobe Illustrator

Not really coding, but still convenient.

How to convert a sketch to an adobe illustrator image

Some handles on how to convert a sketch to an adobe illustrator image.

Import image in Adobe Illustrator, then Window > Image trace. Use that panel to convert. Note that it won’t become vector immediately, instead you’ll still be able to edit the trace through the window. Select Object > Image Trace > Expand to make it into a set of vectors. (Or do this from the options menu.)
http://www.adobepress.com/articles/article.asp?p=1928526&seqNum=3
http://notes.jerzygangi.com/how-to-change-a-line-into-a-shape-in-illustrator/

To paint parts of the image, use Live paint bucket. First select the stuff you want. Later to add more stuff, use Object > Live Paint > Merge. This option is a bit hidden behind the Shape Builder Tool.
https://forums.adobe.com/thread/1107330

Use Object > Path > Outline Stroke, to convert a stroke to a vector object that has borders where the outlines of the stroke path were.

Python

I used the anaconda distribution, python 3.0, and use

$ ipython3

to run python code from command line. (This comes with the Spyder GUI.)
Currently gedit is my favorite editor, and I sometimes copy lines of code from gedit, to paste them in ipython using the magic paste command

>> %paste

. A style guide can be found at python.org.

For Windows, I both tried Anaconda and Python(x,y).

Some convenient parts of Python code

Using color palette by Cynthia Brewer.

# using colorbrewer
import palettable.colorbrewer 
import matplotlib.colors as colors
cmap = colors.ListedColormap(palettable.colorbrewer.diverging.Spectral_6.mpl_colors)                      

theColor = cmap.colors[clusterIndex] # use in line where plotting is done

See https://jiffyclub.github.io/palettable/colorbrewer/ for an overview of the colours.

Misc.

  • I use TeXstudio for Latex editing.
  • I use WinSCP for FTP transfers.

Matlab code

Some convenient parts of Matlab code.

Some standardized plotting code

(Todo.)

Plotting on top of subplot of previously saved figure

When you have saved a figure with subplots, and later want to add to this figure after loading, you can use e.g. h.Children(2) to get to a subplot’s axis. However, if you want to make sure that you have the right subplot, you can use tags. The example below shows how to do this.

%%
testH=figure;
hS1=subplot(1,2,1);
plot(hS1,1:10,2:11);
hS1.Tag='subplot1';

hS2=subplot(1,2,2);
plot(hS2,1:10,2:11);
hS2.Tag='subplot2';

%%
savefig('testTag.fig')
hT=openfig('testTag.fig')

hax = findobj(hT, 'Type', 'axes', 'Tag', 'subplot1');
axes(hax); hold on;
plot([1:10], ones(10,1)*5);

Saving plots

The saveas() function is convenient, but the print function offers more options, you can also set the dpi (use e.g. -r300 to set resolution to 300dpi).

saveas(h1,[OUTPUTFOLDER 'pdf_' figureName '.pdf']);
figure(h1); print([OUTPUTFOLDER 'tif_' figureName '.tif'],'-r300','-dtiff')

Checking whether folder exists, creating it otherwise

currentFolder = pwd;
outputDir = [currentFolder '\output\'];
currentDateTime = datestr(now);
currentDateTime = strrep(currentDateTime, ':', '-');
currentDateTime = strrep(currentDateTime, ' ', '_');
if ~exist(outputDir)
    mkdir(outputDir)
end
save( [outputDir 'simdata_' currentDateTime '.mat'] );

Date time string

datePrefix = ['_' datestr(now,'YYYY-MM-DD') '_' datestr(now,'HH-MM')]

Some conveniences for matlab

%Set all fontsizes
FONTSIZE=20
set(findall(gcf,'type','text'),'FontSize',FONTSIZE,'fontWeight','normal')
set(gca,'FontSize',FONTSIZE)

% Legend with chosen handles
legend([l1,l2,l3,l4],{'description 1','description ','description','description '},'Location','southeast')

Next line in plot title

% 10 is the code for nextline
title( [ 'line 1', 10, 'line 2' ] )

Look of numbers

Editing decimal places:

 sprintf('%0.3f', fitMu)

Adding zeroes at front:

sprintf('%03d', N)

Errorbar plot

% Short:
[h,hErrorbar]=barwitherr([output.stdFluor],[output.meanFluor]); % note weird order
set(hErrorbar, 'LineWidth', 3) 

% Long:
% make errorbar plot
% ===
figure, clf, 
[h,hErrorbar]=barwitherr([output.stdFluor],[output.meanFluor]);
set(hErrorbar, 'LineWidth', 3) %MW added
set(h, 'FaceColor', [.4 .4 .4]);
MW_makeplotlookbetter(14);
title('mean Fluor values');
set(gca, 'XTickLabel',USERSETTINGS.wellNamesToPlot, 'XTick',1:numel(USERSETTINGS.wellNamesToPlot))
ylabel('fluor / OD (a.u.)')

Bars with colors

for i=1:numel(alldata)
    l=bar(i, fittedMus(i));
    set(l, 'LineWidth', 1, 'FaceColor', customcolors(i,:), 'EdgeColor', customcolors(i,:));
end

% align,labeling
set(gca, 'XTickLabel',{1:numel(alldata)}, 'XTick',1:numel(alldata))
xlim([0,numel(alldata)+1])

Save figure, also color vector format

% save the figure 
saveas(1, [MYDIR 'summaryPlot_colonylength.tif'],'tif');
saveas(1, [MYDIR 'summaryPlot_colonylength.eps'],'epsc');

Log scale

plot( [1,2], [3,4]);
set(gca,'xscale','log');

Annoying struct ylim

% Determine ylim
frameSummedLengthdatapile=[];
for i=1:numel(alldata)
    frameSummedLengthdatapile = [frameSummedLengthdatapile, alldata(i).frameData(:).frameSummedLength];
end
ylim([0,max(frameSummedLengthdatapile)*1.1]);

Accessing multiple entries from vectors in a struct

When you’d like to do something like

mystruct(:).(myFieldName)(1) % doesn't work
length(mystruct(:).(myFieldName)) % doesn't work

Do this instead:

lengths = arrayfun(@(x) length(x.(myFieldName)),mystruct)
firstElements = arrayfun(@(x) x.(myFieldName)(1),mystruct)
% x is just parameter for arrayfun.

The same can be done using cellfun, if you want to go over cell entries. Note that in some cases ‘UniformOutput’ can be a convenient parameter.

alltaus = cellfun(@(x) groupedCCLines.(x).tau, DATASETSTOPLOT, 'UniformOutput', false)

Generating nicely colored lines

Use the package

linspecer

. (Maybe check exact copyright of this, seem to be some issues.)

Plotyy with different features

– Make x axis log scale.
– Set x lim.
– Plot another point on specific either axes.
– Choose which line is on top.
– Controlling colors and font sizes of axes.
– Setting axes labels.
– Make it fit the plot window.
– Set ticks.

%% Create dual y-axis optimality plot, 

figure; clf; 

% plot individual well points
% ....
% manualMuValues

% plot lines
muData = [output.muValuesMean];
plateauData = [output.plateauValuesMean];
[ax,l1,l2]  = plotyy(myConcentrations,muData,...
                     myConcentrations,plateauData);%,'semilogx');
set(l1,'Marker','o','LineWidth',3,'Color','r');
set(l2,'Marker','s','LineWidth',2,'Color',[.7 .7 .7]);


hold(ax(1), 'on');
hold(ax(2), 'on');

% x lim
myXlim = [min(myConcentrations(myConcentrations>0))/3,max(myConcentrations)*3];
xlim(ax(1),myXlim);
xlim(ax(2),myXlim);

% plot values at 0
l0 = plot(ax(1),myXlim(1),muData(end));
set(l0,'Marker','o','LineWidth',3,'Color','r');
l0 = plot(ax(2),myXlim(1),plateauData(end));
set(l0,'Marker','s','LineWidth',2,'Color',[.7 .7 .7]);
               
% Put graph 1 on the foreground
% (Thanks to https://nl.mathworks.com/matlabcentral/answers/21181-setting-order-and-transparency-in-plotyy)
uistack(ax(1));
set(ax(1), 'Color', 'none');
set(ax(2), 'Color', 'w');
          
% log scale x axes
set(ax(1),'xscale','log');
set(ax(2),'xscale','log');

% Set cosmetics
set(ax(1),'fontsize',15);
set(ax(2),'fontsize',15);

ylim(ax(1),[0,max(muData)*1.4]);
ylim(ax(2),[min(plateauData),max(plateauData)*1.4]);

MW_makeplotlookbetter(15);

xlabel('Concentration cAMP','Color','k');
ylabel(ax(1),'Growth rate [dbl/hr]','Color','k');
ylabel(ax(2),'OD plateau value [a.u.]','Color','k');
set(ax(1), 'YColor', 'k');
set(ax(2), 'YColor', 'k');

legend([l1,l2],{'Growth rates','Max. OD value observed'})

% Per default larger fonts don't fit this window
set(ax(1), 'Position',[0.15 0.15 0.65 0.8]);

% Set ticks
labelLocations=logspace(1,4,4);
set(gca,'XTick',labelLocations);%'XTickLabel',USERSETTINGS.wellNamesToPlot, 
set(ax(1),'YTick',[0:0.2:1]);%'XTickLabel',USERSETTINGS.wellNamesToPlot, 

Set figure size for saving

h=figure();
h.PaperUnits = 'centimeters';
h.PaperPosition = [0 0 13.1 6.6];
saveas(h, ...);

Aligning subplots and legends

Introducing separate legends to subplot introduces misalignments. Below solves it, first prat is for plots, second for legends. Code is a bit sloppy, the code for the legend is cleaner imo.

% Align plots
pos=get(axes,'position')
pmat=cat(1,pos{:});
%define new postions
nax=numel(axes);
pnew=repmat(max(pmat),nax,1);
pnew(:,1)=pmat(:,1); %keep old left pos
pnew(:,2)=pmat(:,2); %keep old left pos
pnew(:,4)=pmat(:,4); %keep old left pos
newpos = num2cell(pnew,2);
%apply new positions
set(axes,{'position'},newpos)

% Align legends
pos=get(leg,'position')
%pmat=cat(1,pos{:});
posmat=cell2mat(pos)
left  = posmat(:,1);
sizes = posmat(:,3);
posmat(:,1) = ones(3,1)*min(left);
%posmat(:,1) = 1-max(sizes);
posmat(:,3) = ones(3,1)*max(sizes);
% set
set(leg,{'position'},num2cell(posmat,2))

Figures without focus

How to generate and save figures in matlab that are invisible and do not “steal” focus from other programs, i.e. how to make figures in the background.

% use this option to make invisible figure:
h1=figure('Visible','off');
% to go back to this figure (e.g. to add more data to it), use
set(0,'CurrentFigure',h1); % instead of figure(h1).

Create subplot meta titles and labels for axes

I downloaded the function subtitle for this, and edited it to also add axes titles.

function [ax,h]=subtitle_mw(text,theXLabel,theYLabel)
%
% SOURCE: https://nl.mathworks.com/matlabcentral/answers/100459-how-can-i-insert-a-title-over-a-group-of-subplots
% USER:   MathWorks Support Team
%
%Centers a title over a group of subplots.
%
%Returns a handle to the title and the handle to an axis.
%
% [ax,h]=subtitle(text)
%
%           returns handles to both the axis and the title.
%
% ax=subtitle(text)
%
%           returns a handle to the axis only.

% Create an invisible axis that covers all the subplots
ax=axes('Units','Normal','Position',[.075 .05 .85 .9],'Visible','off');
%ax=axes('Units','Normal','Position',[.075 .075 .85 .85]);%,'Visible','off'); % original

% Remove ticklabels
set(ax, 'XTickLabel', []);
set(ax, 'YTickLabel', []);

% Set desired components to visible
set(get(ax,'Title'),'Visible','on')
set(get(ax,'xlabel'),'Visible','on')
set(get(ax,'ylabel'),'Visible','on')

% print the desired components
title(text);
xlabel(theXLabel);
ylabel(theYLabel);

% some additional output
if (nargout < 2)

    return

end

h=get(ax,'Title');

Getting a desired line on top of the stack of your figure

uistack(lineHandle,'top');

Some software packages recommended by SH

Python and all the typical SciPy stuff for data analysis
http://www.scipy.org

PostgreSQL - a SQL database server
http://www.postgresql.org

SQLalchemy - magic SQL database manipulation in Python
http://www.sqlalchemy.org

Flask - easy web server/apps in Python
http://flask.pocoo.org

REST API - for communicating between web apps
http://www.restapitutorial.com

JSON - the data format for transmitting data between apps
http://www.json.org

JQuery - JavaScript library for doing fancy web apps
https://jquery.com

Highcharts - JavaScript chart library
http://www.highcharts.com

Leave a Reply

Your email address will not be published. Required fields are marked *