Specify how many ticks one needs

from matplotlib.ticker import LogLocator
ax.yaxis.set_major_locator(LogLocator(numticks=6))

This is for a loglog plot. There is another function for regular plot called MaxNLocator.

Why not using set_ticks? The situation is that I do not know where the ticks are and python does a good job in determining the location of ticks.

Parallelize big for loops in python

Suppose I have a big for loop to run (big in the sense of many iterations):

for i in range(10000)
   for j in range(10000)
       f((i,j)) 

After hours of search I arrived at the solution using “multiprocessing” module, as the following:

pool=Pool()
x=pool.imap(f,((i,j) for i in xrange(10000) for j in xrange(10000)]))

Remark: pool.map would generate a list of arguments first and then feed the list to the function. Hence if I have a big for loop, it spends a lot of time generating the list of arguments using only 1 cpu. In contrast, imap would generate the arguments on the fly, therefore parallelizing the for loop as I wish.

Coloring curves automatically

If you are to plot a bunch of curves in one figure and tired of color-coding each curve by hand, I have wrote this function which generates a color for each curve. What it needs is a parameter whose values correspond to different curves. For example, one has 3 time series stored in a 3-by-T matrix X. The three series correspond to a parameter temp=0, 0.4, 0.9 respectively. To plot each series in a different color,

figure;
hold on;
temp=[0, 0.4, 0.9];
for i=1:3
    plot(X(:,i),'color',paintcolor(temp(i),min(temp),max(temp)));
end

Legend in matlab

Show legend for some of the curves in the figure and skip the other curves.

figure;
hold on;
h1=plot(x1,y1);
h2=plot(x2,y2);
...
legend([h1 h2], 'x1y1', 'x2y2');

Break the legend into different boxes (show legend for each curve separately). The idea is to show different legend in different axes.

figure;
hold on;
h1=plot(x1,y1);
h2=plot(x2,y2);
ax1=axes('position',get(gca,'position'),'visible','off');
legend(ax1,h1,'x1y1');
ax2=axes('position',get(gca,'position'),'visible','off');
legend(ax2,h2,'x2y2');