Archive for the ‘plotting’ Category

Polar bar plot in Python

Sunday, July 20th, 2008

Here’s how to create a polar bar plot in matplotlib.


The trick is just to specify that you want polar coordinates when you create the axis. Then create a bar plot as normal.

from matplotlib.pyplot import figure, show
from math import pi

fig = figure()
ax = fig.add_subplot(111, polar=True)
x = [30,60,90,120,150,180]
x = [i*pi/180 for i in x]  # convert to radians

ax.bar(x,[1,2,3,4,5,6], width=0.4)
show()

Note that in the above example the “right” or “clockwise-most” edge is lined up with each specified x value. You can change this by subtracting width / 2 to each of the x values to center the bars on the x-values, like this:

from matplotlib.pyplot import figure, show
from math import pi

width = 0.4  # width of the bars (in radians)

fig = figure()
ax = fig.add_subplot(111, polar=True)
x = [30,60,90,120,150,180]

# Convert to radians and subtract half the width
# of a bar to center it.
x = [i*pi/180 - width/2 for i in x]
ax.bar(x,[1,2,3,4,5,6], width=width)
show()

Get funky . . .

The following is slightly modifed from the matplotlib examples:

import numpy as npy
import matplotlib.cm as cm
from matplotlib.pyplot import figure, show, rc

# force square figure and square axes (looks better for polar, IMHO)
fig = figure(figsize=(8,8))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)

N = 20
theta = npy.arange(0.0, 2*npy.pi, 2*npy.pi/N)  # random angles
radii = 10*npy.random.rand(N)  # random bar heights
width = npy.pi/4*npy.random.rand(N) # random widths

# Create the bar plot
bars = ax.bar(theta, radii, width=width, bottom=0.0)

# Step through bars (a list of Rectangle objects) and
# change color based on its height and set its alpha transparency
# to 0.5

for r,bar in zip(radii, bars):
    bar.set_facecolor( cm.jet(r/10.))
    bar.set_alpha(0.5)

show()

And the result:

Interactive subplots: make all x-axes move together

Saturday, May 3rd, 2008

It’s very easy to make subplots that share an x-axis, so that when you pan and zoom on one axis, the others automatically pan and zoom as well. The key to this functionality is the sharex keyword argument, which is used when creating an axis. Here’s some example code and a video of the resulting interaction. (more…)

Change properties of ggplot plots

Monday, February 4th, 2008

Try

?ggopt

to see the different ways of adjusting plot background, axes, aspect ratio, border colors, and strip labels.

Change the font size of the labels.

This acts on the currently active plot.

grid.gedit('label', gp=gpar(fontsize=16))

Or just change one type of label (here, the yaxis).

grid.gedit(gPath("yaxis", "labels"), gp=gpar(col="red"))

Use a black and white theme

The newest version of ggplot2 (0.5.7) allows you to have black and white themes.

pl = ggplot(diamonds)+aes(x=carat, y=price) +
    geom_point()+theme_bw
pl

I like to tweak the theme_bw a little before using it as above:

theme_bw$grid.colour = "grey80"
theme_bw$border.colour = "gray70"

Change the strip labels

pl$strip.gp = gpar(fill="grey90")
pl$strip.txt.gp = gpar(col="black", fontsize=16)
pl

Change factor colors to grayscale

pl+scale_colour_grey(end=0.7,start=0,name='')
pl

Interactively select points from a plot in matplotlib

Monday, January 28th, 2008

In Matlab, there is a very useful function called ginput(). There is no such ready-built function for matplotlib/pylab, but all the pieces are there. Copy and paste this code to get ginput functionality.
(more…)

Errorbars in matplotlib

Sunday, January 27th, 2008

Here’s how to plot x or y errorbars (or both) and how to customize the resulting plot.
(more…)

Adjust settings for matplotlib using rc and matplotlibrc

Monday, January 21st, 2008

The matplotlibrc file contains many useful parameters for tweaking your setup to your liking, and it’s worth at least skimming through to get an idea of what it contains. Editing the file makes more permanent changes, while using the pylab rcParams dictionary or rc() and rcdefaults() functions lets you make and revert changes on the fly.

View the rc parameters by using

import pylab as p
print p.rcParams

Examples ensue.
(more…)

Change distance of tick labels from axis

Thursday, January 17th, 2008

Set the rc parameters using the rc function.


import pylab as p
p.rc(('xtick.major','xtick.minor','ytick.major','ytick.minor'), pad=10)
p.plot([1,2,3])

If you only want to change one of the tick labels, say, the x major ticks, use
p.rc(’xtick.major), pad=10)

When you’re done and want to reset the rc settings, use

p.rcdefaults()

See matplotlibrc for more settings you can change via the rc command.

Interacting with figures in Python

Thursday, January 17th, 2008

Here is some code from the matplotlib mailing list, sent by Rob Hetland, for selecting points from a plot.


from matplotlib.pyplot import *

class ginput(object):
    """docstring for on_click"""

    def __init__(self):
        self.x = []
        self.y = []
        connect('button_press_event', self)

    def __call__(self, event):
        xd, yd = event.xdata, event.ydata
        if event.button==1:
            if event.inaxes is not None:
                # print 'data coords', event.xdata, event.ydata
                self.x.append(xd)
                self.y.append(yd)
                plot((xd,), (yd,), 'r+', ms=5)

map_points = ginput()

#!/usr/bin/env python
# encoding: utf-8
"""Polygon geometry.

Copyright (C) 2006, Robert Hetland
Copyright (C) 2006, Stefan van der Walt

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the
   distribution.
3. The name of the author may not be used to endorse or promote
   products derived from this software without specific prior written
   permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""

import numpy as np
import sys

try:
    import scipy.weave as weave

    def npnpoly(verts,points):
        verts = verts.astype(np.float64)
        points = points.astype(np.float64)

        xp = np.ascontiguousarray(verts[:,0])
        yp = np.ascontiguousarray(verts[:,1])
        x = np.ascontiguousarray(points[:,0])
        y = np.ascontiguousarray(points[:,1])
        out = np.empty(len(points),dtype=np.uint8)

        code = """
        /* Code from:
           http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

           Copyright (c) 1970-2003, Wm. Randolph Franklin

           Permission is hereby granted, free of charge, to any person
           obtaining a copy of this software and associated documentation
           files (the "Software"), to deal in the Software without
           restriction, including without limitation the rights to use, copy,
           modify, merge, publish, distribute, sublicense, and/or sell copies
           of the Software, and to permit persons to whom the Software is
           furnished to do so, subject to the following conditions:

        	1. Redistributions of source code must retain the above
                 copyright notice, this list of conditions and the following
                 disclaimers.
        	2. Redistributions in binary form must reproduce the above
                 copyright notice in the documentation and/or other materials
                 provided with the distribution.
        	3. The name of W. Randolph Franklin may not be used to endorse
                 or promote products derived from this Software without
                 specific prior written permission.

           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
           EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
           MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
           NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
           BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
           ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
           CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
           SOFTWARE. */

        int i,j,n;
        unsigned int c;
        int nr_verts = Nxp[0];
        for (n = 0; n < Nx[0]; n++) {
            c = 0;
        	for (i = 0, j = nr_verts-1; i < nr_verts; j = i++) {
                if ((((yp(i)<=y(n)) && (y(n)= 3, 'Need 3 vertices to create polygon.'

        # close polygon, if needed
        if not np.all(verts[0]==verts[-1]):
            verts = np.vstack((verts,verts[0]))

        self.verts = verts

        return verts.view(Polygeom).copy()

    def inside(self,points):
        points = np.atleast_2d(points)
        assert points.shape[1] == 2, \
               "Points should be of shape Nx2, is %s" % str(points.shape)
        return npnpoly(self.verts,points).astype(bool)

    def get_area(self):
        """
        Return the area of the polygon.

        From Paul Bourke's webpage:
          http://astronomy.swin.edu.au/~pbourke/geometry
        """
        v = self.verts
        v_first = v[:-1][:,[1,0]]
        v_second = v[1:]
        return np.diff(v_first*v_second).sum()/2.0

    def get_centroid(self):
        "Return the centroid of the polygon"
        v = self.verts
        a = np.diff(v[:-1][:,[1,0]]*v[1:])
        area = a.sum()/2.0
        return ((v[:-1,:] + v[1:,:])*a).sum(axis=0) / (6.0*area)

    area = property(get_area)
    centroid = property(get_centroid)

if __name__ == '__main__':
    import pylab as pl
    grid = np.mgrid[0:1:10j,0:1:10j].reshape(2,-1).swapaxes(0,1)

    # simple area test
    verts = np.array([[0.15,0.15],
                      [0.85,0.15],
                      [0.85,0.85],
                      [0.15,0.85]])
    pa = Polygeom(verts)
    print pa.area
    print (0.85-0.15)**2

    print pa

    print pa.centroid

    # concave enclosure test-case for inside.
    verts = np.array([[0.15,0.15],
                      [0.25,0.15],
                      [0.45,0.15],
                      [0.45,0.25],
                      [0.25,0.25],
                      [0.25,0.55],
                      [0.65,0.55],
                      [0.65,0.15],
                      [0.85,0.15],
                      [0.85,0.85],
                      [0.15,0.85]])
    pb = Polygeom(verts)
    inside = pb.inside(grid)
    pl.plot(grid[:,0][inside], grid[:,1][inside], 'g.')
    pl.plot(grid[:,0][~inside], grid[:,1][~inside],'r.')
    pl.plot(pb.verts[:,0],pb.verts[:,1], '-k')
    print pb.centroid
    xc, yc = pb.centroid
    print xc, yc
    pl.plot([xc], [yc], 'co')
    pl.show()

    pl.figure()
    # many points in a semicircle, to test speed.
    grid = np.mgrid[0:1:1000j,0:1:1000j].reshape(2,-1).swapaxes(0,1)
    xp = np.sin(np.arange(0,np.pi,0.01))
    yp = np.cos(np.arange(0,np.pi,0.01))
    pc = Polygeom(np.hstack([xp[:,np.newaxis],yp[:,np.newaxis]]))
    print "%d points inside %d vertex poly..." % (grid.size/2,len(verts)),
    sys.stdout.flush()
    inside = pc.inside(grid)
    print "done."
    pl.plot(grid[:,0][inside], grid[:,1][inside], 'g+')
    pl.plot(grid[:,0][~inside], grid[:,1][~inside], 'r.')
    pl.plot(pc.verts[:,0], pc.verts[:,1], '-k')
    xc, yc = pc.centroid
    print xc, yc
    pl.plot([xc], [yc], 'co')
    pl.show()