Tuesday, June 23, 2009

Transparent legend in your plots

Have you ever made a plot with several data series together and found that there is no way to put an explanatory legend onto the plot without hiding crucial data points? One answer to this problem can be to overlay a transparent legend. There are two routes to this "graphical goodness" that I would immediately think about:

  • Create an image file from your plot and then "photoshop" it (or gimp it...)
  • Add the alpha channel directly in the plotting tool...
Matlab can possibly do this, I really don't know. Here's how to do it in python. Say you have some data you want to plot, for example the sine and cosine function. Then you'd overlay a transparent key to your data. Let's dive in..

from pylab import * t = linspace(-2*pi,2*pi) y1=cos(t); y2=sin(t); plot(t,y1,label='Cosine') plot(t,y2,label='Sine') xlabel('Time') ylabel('y')
axis([-2*pi,2*pi,-1,1])
leg=legend()
savefig('namehere.png')
close()

Now we see from the resulting plot that the legend covers some of the graph. Now, before the "savefig" command, add the following:
frame=leg.get_frame()
frame.set_alpha(0.4)


The resulting plot is shown below the original. Better, don't you think? :-)

PS! Click on the plots to show larger versions!

No comments:

Post a Comment