<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>scienceoss.com &#187; matplotlib</title>
	<atom:link href="http://scienceoss.com/categories/python/matplotlib/feed/" rel="self" type="application/rss+xml" />
	<link>http://scienceoss.com</link>
	<description>useful tidbits for using open source software in science</description>
	<lastBuildDate>Wed, 26 May 2010 03:34:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Polar bar plot in Python</title>
		<link>http://scienceoss.com/polar-bar-plot-in-python/</link>
		<comments>http://scienceoss.com/polar-bar-plot-in-python/#comments</comments>
		<pubDate>Sun, 20 Jul 2008 14:43:06 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[plotting]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=10</guid>
		<description><![CDATA[Here&#8217;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. Note that in the above example the &#8220;right&#8221; or &#8220;clockwise-most&#8221; edge is lined up with each specified x value. You can change [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s how to create a polar bar plot in matplotlib.</p>
<p><br style="clear:both;"></p>
<p>The trick is just to specify that you want polar coordinates when you create the axis.  Then create a bar plot as normal.</p>
<pre class="brush: python; title: ; notranslate">
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()
</pre>
<p><a href="http://scienceoss.com/wp-content/uploads/2008/07/polar-bar-plot-simple.png"><img src="http://scienceoss.com/wp-content/uploads/2008/07/polar-bar-plot-simple-300x225.png" alt="" title="polar-bar-plot-simple" width="300" height="225" class="alignnone size-medium wp-image-136" /></a></p>
<p>Note that in the above example the &#8220;right&#8221; or &#8220;clockwise-most&#8221; edge is lined up with each specified x value.  You can change this by subtracting <span class="c">width / 2</span> to each of the x values to center the bars on the x-values, like this:</p>
<pre class="brush: python; title: ; notranslate">
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()
</pre>
<p><a href="http://scienceoss.com/wp-content/uploads/2008/07/polar-bar-plot-simple-centered.png"><img src="http://scienceoss.com/wp-content/uploads/2008/07/polar-bar-plot-simple-centered-300x225.png" alt="" title="polar-bar-plot-simple-centered" width="300" height="225" class="alignnone size-medium wp-image-137" /></a></p>
<h3>Get funky . . . </h3>
<p>The following is slightly modifed from the matplotlib examples:</p>
<pre class="brush: python; title: ; notranslate">
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()
</pre>
<p>And the result:</p>
<p><a href="http://scienceoss.com/wp-content/uploads/2008/07/polar-bar-plot-alpha.png"><img src="http://scienceoss.com/wp-content/uploads/2008/07/polar-bar-plot-alpha-300x300.png" alt="" title="polar-bar-plot-alpha" width="300" height="300" class="alignnone size-medium wp-image-135" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/polar-bar-plot-in-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Interactive subplots: make all x-axes move together</title>
		<link>http://scienceoss.com/interactive-subplots-make-all-x-axes-move-together/</link>
		<comments>http://scienceoss.com/interactive-subplots-make-all-x-axes-move-together/#comments</comments>
		<pubDate>Sat, 03 May 2008 18:27:25 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[plotting]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[axes]]></category>
		<category><![CDATA[intertactive plotting]]></category>
		<category><![CDATA[subplot]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=123</guid>
		<description><![CDATA[It&#8217;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&#8217;s some example code and a video of the resulting [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;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 <span class="c">sharex</span> keyword argument, which is used when creating an axis.  Here&#8217;s some example code and a video of the resulting interaction.<span id="more-123"></span></p>
<pre class="brush: python; title: ; notranslate">
from pylab import figure, show

# Create some data: one x, three different y
x = arange(0.0, 20.0, 0.01)
y1 = sin(2*pi*x)
y2 = exp(-x)
y3 = y1*y2

# Create a figure and add three subplots.
fig = figure()
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312, sharex=ax1)  # share ax1's xaxis
ax3 = fig.add_subplot(313, sharex=ax1)  # share ax1's xaxis

# Plot
ax1.plot(x,y1)
ax2.plot(x,y2)
ax3.plot(x,y3)

# Show the figure.
show()
</pre>
<p>Here&#8217;s a video of what the interaction is like with this figure (matplotlib automatically adds the pan, zoom, home, etc buttons to all figures):</p>
<p><embed src="http://www.jeroenwijering.com/embed/player.swf" width="320" height="250" allowscriptaccess="always" allowfullscreen="true" flashvars="height=250&#038;width=320&#038;file=http://scienceoss.com/wp-content/uploads/2008/04/out.flv&#038;searchbar=false"/></p>
<p>Notice that the y-axis remained independent in each of the three subplots.  As you&#8217;d expect, the <span class="c">add_subplot()</span> method accepts a <span class="c">sharey</span> keyword argument as well.  You can even pass both <span class="c">sharex</span> and <span class="c">sharey</span> . . . this is most useful when two subplots show data with the same units.</p>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/interactive-subplots-make-all-x-axes-move-together/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Interactively select points from a plot  in matplotlib</title>
		<link>http://scienceoss.com/interactively-select-points-from-a-plot-in-matplotlib/</link>
		<comments>http://scienceoss.com/interactively-select-points-from-a-plot-in-matplotlib/#comments</comments>
		<pubDate>Mon, 28 Jan 2008 19:30:15 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[plotting]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[ginput]]></category>
		<category><![CDATA[interactive]]></category>
		<category><![CDATA[select points]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=14</guid>
		<description><![CDATA[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. The code is below if you want to jump right to it. Here&#8217;s a little explanation of what&#8217;s happening: The general idea [...]]]></description>
			<content:encoded><![CDATA[<p>In Matlab, there is a very useful function called <span class="c">ginput()</span>.  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.<br />
<span id="more-14"></span><br />
The code is below if you want to jump right to it.</p>
<p>Here&#8217;s a little explanation of what&#8217;s happening:</p>
<p>The general idea is to create a class, the <span class="c">MouseMonitor</span>, that will hold the x and y data coordinates.  This class has a single method, the <span class="c">mycall()</span> method.  <em>Note: you could be tricky and define a <span class="c">__call__</span> method, and save a few keystrokes by just passing <span class="c">mouse</span> (instead of <span class="c">mouse.mycall</span>) to the <span class="c">connect</span> function.  I didn&#8217;t do that here cause it&#8217;s harder to explain.</em></p>
<p>The <span class="c">connect()</span> function needs, as its first argument, the name of an event.  Possible events are &#8216;resize_event&#8217;, &#8216;draw_event&#8217;, &#8216;key_press_event&#8217;, &#8216;key_release_event&#8217;, &#8216;button_press_event&#8217;, &#8216;button_release_event&#8217;, &#8216;motion_notify_event&#8217;, and &#8216;pick_event&#8217;.</p>
<p>The second argument to <span class="c">connect()</span> needs to be the name of a function that will be called every time that event happens.  In this case, it&#8217;s the <span class="c">mycall</span> method of the <span class="c">mouse</span> object, <span class="c">mouse.mycall</span>.</p>
<p>Since mouse.mycall is the callback function given to connect, it will be called every time there is a button press event.  So every time you click on the plot, <span class="c">mouse.mycall</span> it will append the x and y coords to its own internal list, print the x and y coords, plot a red circle, and refresh the plot every time.</p>
<p>When you&#8217;re done, you can access the x and y data in mouse with <span class="c">mouse.xdatalist</span> and <span class="c">mouse.ydatalist</span>.</p>
<p>More examples to follow, but for now here&#8217;s a basic version that improve a little on the functionality of Matlab&#8217;s ginput (which doesn&#8217;t give you graphical feedback on its own).</p>
<pre class = "prettyprint"><code class = "code">
from pylab import *
class MouseMonitor:
    event = None
    xdatalist = []
    ydatalist = []

    def mycall(self, event):
        self.event = event
        self.xdatalist.append(event.xdata)
        self.ydatalist.append(event.ydata)

        print 'x = %s and y = %s' % (event.xdata,event.ydata)

        ax = gca()  # get current axis
        ax.hold(True) # overlay plots.

        # Plot a red circle where you clicked.
        ax.plot([event.xdata],[event.ydata],'ro')

        draw()  # to refresh the plot.

if __name__=="__main__":
    # Example usage
    mouse = MouseMonitor()
    connect('button_press_event', mouse.mycall)
    plot([1,2,3])
    show()
</code></pre>
<h2>An improved version</h2>
<p>The following code allows you to set up a MouseMonitor object that plots multiple sets of data.</p>
<pre class="prettyprint"><code class="code">from pylab import *
import sys
class MouseMonitor:
    event = None
    xdatalist = []
    ydatalist = []

    def my_call(self, event):
        self.event = event

        if event.button == 1:
            self.xdatalist.append(event.xdata)
            self.ydatalist.append(event.ydata)

            sys.stdout.flush()
            print 'x = %s and y = %s' % (event.xdata,event.ydata)
            sys.stdout.flush()
            ax = gca()
            ax.hold(True)
            ax.plot([event.xdata],[event.ydata],'ro')

            draw()

        if event.button == 3:
            disconnect(self.cid)
            self.ask_for_another()

    def ask_for_another(self):
        sys.stdout.flush()
        answer = raw_input('Press n for the next plot, or any other key to stop:  ')
        if answer == 'n':
            self.plot_next()
        else:
            print '::sniff::  bye'
            close('all')

    def set_data(self,x,y):
        self.xlist = x
        self.ylist = y
        self.i = 0

    def plot_next(self):
        if self.i < len(self.xlist):
            cla()
            plot(xlist[self.i],ylist[self.i])
            self.i += 1
            self.connect_to_plot()
            draw()
        else:
            sys.stdout.flush()
            print 'all out of data.'

    def connect_to_plot(self):
        self.cid = connect('button_press_event',self.my_call)

if __name__ == "__main__":
    mouse = MouseMonitor()

    xlist = [[1,2,3],[4,5,6]]
    ylist = [[3,4,5],[8,9,7]]

    mouse.set_data(xlist,ylist)

    mouse.plot_next()

    show()</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/interactively-select-points-from-a-plot-in-matplotlib/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Errorbars in matplotlib</title>
		<link>http://scienceoss.com/errorbars-in-matplotlib/</link>
		<comments>http://scienceoss.com/errorbars-in-matplotlib/#comments</comments>
		<pubDate>Sun, 27 Jan 2008 17:50:58 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[plotting]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[marker]]></category>
		<category><![CDATA[pylab]]></category>
		<category><![CDATA[standard deviation]]></category>
		<category><![CDATA[standard error]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=78</guid>
		<description><![CDATA[Here&#8217;s how to plot x or y errorbars (or both) and how to customize the resulting plot. Note: As always, the docstrings are wonderful things. After importing, use ?errorbar at the IPython prompt to view the help. For these plots, I&#8217;m assuming the code in the &#8220;Setup&#8221; section below has been run (to import pylab [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s how to plot x or y errorbars (or both) and how to customize the resulting plot.<br />
<span id="more-78"></span><br />
Note: As always, the docstrings are wonderful things.  After importing, use <span class="c"><strong>?errorbar</strong></span> at the IPython prompt to view the help.</p>
<p>For these plots, I&#8217;m assuming the code in the &#8220;Setup&#8221; section below has been run (to import pylab and to create some fake data).</p>
<ul>
<li>x is the x data</li>
<li>y is the y data</li>
<li>e, f, g, and h are different errors.  Why four?  Because not only can you have horizontal and vertical errorbars but you can have asymmetrical error bars as well.  It&#8217;s possible to plot four different errors for each point in the four directions -x, +x, -y and +y.</li>
</ul>
<p>Note that the errors are randomly generated, so the plots below won&#8217;t exactly like your plots even if you run the same code.</p>
<h3>Getting your own error estimates</h3>
<p>Here is an excellent and <em>very</em> readable <a href="http://ww1.cpa-apc.org:8080/publications/archives/PDF/1996/Oct/strein2.pdf">differences between standard error and standard deviation and when to use each</a>.  Guaranteed you&#8217;ll feel more comfortable about standard error and standard deviation after reading this.</p>
<p>If you need to generate your own error bars, you can use (for example) the NumPy function <span class="c">std()</span> &#8212; but be warned: this function divides by N, not N-1 (degrees of freedom) so be careful with small sample sizes.</p>
<h3>The setup (will be assumed for all following code)</h3>
<p>If you started IPython with the -pylab switch, the plots should show up immediately when you use the plotting commands below.</p>
<p>If you did not start IPython with the -pylab switch, then you will need to type <span class="c">show()</span> to display the plots.  You will also have to close all plots before being able to get back to the command line.</p>
<pre class = "prettyprint"><code class = "code">
from pylab import *

x = arange(0.1, 4, 0.1)
y = exp(-x)
e = 0.1*abs(randn(len(y)))
f = 0.1*abs(randn(len(y)))
g = 2*e
h = 2*f
</code></pre>
<h3>Vertical symmetric errorbars</h3>
<p><em>(probably the most common use)</em><br />
This one has red circles as the marker format, &#8220;<span class="c">ro</span>&#8220;.</p>
<pre class = "prettyprint"><code class = "code">
figure()
errorbar(x, y, yerr=e, fmt='ro')
</code></pre>
<div id="attachment_131" class="wp-caption alignnone" style="width: 310px"><a href="http://scienceoss.com/wp-content/uploads/2008/07/vertical_error_bars.png"><img src="http://scienceoss.com/wp-content/uploads/2008/07/vertical_error_bars-300x225.png" alt="Vertical error bars" title="vertical_error_bars" width="300" height="225" class="size-medium wp-image-131" /></a><p class="wp-caption-text">Vertical error bars</p></div>
<h2>Horizontal symmetric errorbars</h2>
<p>This one has a format of blue dots (&#8220;b.&#8221;) and instead of using &#8220;<span class="c">yerr</span>&#8221; uses &#8220;<span class="c">xerr</span>&#8221;</p>
<pre class = "prettyprint"><code class = "code">figure()
errorbar(x, y, xerr=f, fmt='b.')</code></pre>
<div id="attachment_130" class="wp-caption alignnone" style="width: 310px"><a href="http://scienceoss.com/wp-content/uploads/2008/07/horizontal_error_bars.png"><img src="http://scienceoss.com/wp-content/uploads/2008/07/horizontal_error_bars-300x225.png" alt="Horizontal error bars" title="horizontal_error_bars" width="300" height="225" class="size-medium wp-image-130" /></a><p class="wp-caption-text">Horizontal error bars</p></div>
<h2>Symmetric <span class="c">x</span> and symmetric <span class="c">y</span></h2>
<p>Back to the red circles.  This time, both <span class="c">xerr</span> and <span class="c">yerr</span> are used.</p>
<pre class = "prettyprint"><code class = "code">
figure()
errorbar(x, y, yerr=e, xerr=f, fmt='ro')
</code></pre>
<div id="attachment_128" class="wp-caption alignnone" style="width: 310px"><a href="http://scienceoss.com/wp-content/uploads/2008/07/error_bars_both.png"><img src="http://scienceoss.com/wp-content/uploads/2008/07/error_bars_both-300x225.png" alt="Symmetrical error bars" title="error_bars_both" width="300" height="225" class="size-medium wp-image-128" /></a><p class="wp-caption-text">Symmetrical error bars</p></div>
<h2>Asymmetric error bars</h2>
<p>The trick for asymmetric error bars is to pass a list-of-lists (or a 2-D array) as <span class="c">xerr</span> and <span class="c">yerr</span>.  The item in the list is for negative error, the second one for positive error.  So in this case, -y error is <span class="c">e</span>, +y is <span class="c">g</span>, -x is <span class="c">f</span>, and +x is <span class="c">h</span>.</p>
<pre class = "prettyprint"><code class = "code">figure()
errorbar(x, y, yerr=[e,g], xerr=[f,h], fmt='ro')
</code></pre>
<div id="attachment_127" class="wp-caption alignnone" style="width: 310px"><a href="http://scienceoss.com/wp-content/uploads/2008/07/error_bars_asymmetric.png"><img src="http://scienceoss.com/wp-content/uploads/2008/07/error_bars_asymmetric-300x225.png" alt="Aysmmetric error bars" title="error_bars_asymmetric" width="300" height="225" class="size-medium wp-image-127" /></a><p class="wp-caption-text">Aysmmetric error bars</p></div>
<h2>Customizing</h2>
<p>Here&#8217;s an example of the kinds of things you can change in a plot.  See the help for <span class="c">plot</span> and <span class="c">errorbar</span> for more.</p>
<p>In this case I made the points be dots, made the line color black, gave the errorbars a red color, made the markers blue, gave the series a label, changed the errorbar cap size to zero, and made the line style a solid line.</p>
<p>Then I added 0.5 to the y values for a quick way of getting a second line.  I plotted this second line with different formatting commands.</p>
<p>Then I added x and y axis labels, a legend (which used the labels provided in the plotting commands) and finally a title.</p>
<pre class = "prettyprint"><code class = "code">
errorbar(x, y,
           yerr=e,
           marker='.',
           color='k',
           ecolor='r',
           markerfacecolor='b',
           label="series 1",
           capsize=0,
           linestyle='-')

# Add a second series with different errorbar formatting.
errorbar(x, y+0.5,
           yerr=h,
           marker='o',
           color='k',
           ecolor='k',
           markerfacecolor='g',
           label="series 2",
           capsize=5,
           linestyle='None')

xlabel('x axis label')
ylabel('y axis label')
legend()
title('Customized plot with errorbars')
</code></pre>
<p>Yep, it&#8217;s ugly . . . please don&#8217;t use these formatting choices in real life!  My intention here is just to show you how to make tweaks to your plot.<br />
<div id="attachment_129" class="wp-caption alignnone" style="width: 310px"><a href="http://scienceoss.com/wp-content/uploads/2008/07/error_bars_customized.png"><img src="http://scienceoss.com/wp-content/uploads/2008/07/error_bars_customized-300x225.png" alt="Custom error bars" title="error_bars_customized" width="300" height="225" class="size-medium wp-image-129" /></a><p class="wp-caption-text">Custom error bars</p></div></p>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/errorbars-in-matplotlib/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Adjust settings for matplotlib using rc and matplotlibrc</title>
		<link>http://scienceoss.com/adjust-settings-for-matplotlib-using-rc-and-matplotlibrc/</link>
		<comments>http://scienceoss.com/adjust-settings-for-matplotlib-using-rc-and-matplotlibrc/#comments</comments>
		<pubDate>Tue, 22 Jan 2008 04:30:52 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[plotting]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[matplotlibrc]]></category>
		<category><![CDATA[pylab]]></category>
		<category><![CDATA[rc]]></category>
		<category><![CDATA[settings]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=69</guid>
		<description><![CDATA[The matplotlibrc file contains many useful parameters for tweaking your setup to your liking, and it&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>The matplotlibrc file contains many useful parameters for tweaking your setup to your liking, and it&#8217;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.</p>
<p>View the rc parameters by using</p>
<pre class = "prettyprint"><code class = "code">import pylab as p
print p.rcParams</code></pre>
<p>Examples ensue.<br />
<span id="more-69"></span></p>
<h3>Where is matplotlibrc?</h3>
<p>On my machine (Ubuntu 7.10) it&#8217;s in <span class="c">/usr/lib/python2.5/site-packages/matplotlib/mpl-data/matplotlibrc</span>.  If I wanted to customize it, I could put a copy in ~/.matplotlib/matplotlibrc.  If you&#8217;re on Windows, you can put a copy in <span class="c">C:\Documents and Settings\yourname\.matplotlib</span></p>
<p>Editing this file makes changes that are in effect every time you use matplotlib.</p>
<p>To make temporary changes, use the <code>pylab.rc</code> function or set values in the <span class="c">rcParams</span> dictionary.  I&#8217;ll describe both ways below.</p>
<h3>An example</h3>
<p>For example, I want to make a series of plots for a manuscript.  The default font size is a little too small for these plots, and tweaking the font size for every one of the plots would be tedious.  Let&#8217;s see what my rc options are.</p>
<pre class = "prettyprint"><code class = "code">
import pylab as p
p.rcParams
</code></pre>
<p>Among a large number of options, I see some that will be of use:</p>
<pre class = "prettyprint"><code class = "code">...
...
'axes.labelsize': 12.0,
...
'xtick.labelsize': 12.0,
...
'ytick.labelsize': 12,0,
...
</code></pre>
<h3>Two ways to change settings</h3>
<p>It&#8217;s personal preference which one you use.  Either way, you only have to do this once.  From then on, all plots will use these new parameters, until you reset the parameters using <span class="c">rcdefaults()</span></p>
<p>Using rcParams, I could set the properties like this:</p>
<pre class = "prettyprint"><code class = "code">
rcParams['axes.labelsize'] = 16.0
p.rcParams['xtick.labelsize'] = 16.0
p.rcParams['ytick.labelsize'] = 16.0</code></pre>
<p>Alternatively, I could use rc:</p>
<pre class = "prettyprint"><code class = "code">
p.rc(('xtick','ytick','axes'), labelsize=16.0)
</code></pre>
<h3>Now, plot!</h3>
<pre class = "prettyprint"><code class = "code">
p.plot([1,2,3])
p.xlabel('x axis')
p.ylabel('y axis')
p.show()
</code></pre>
<p>Here&#8217;s the new figure.  Any other figure I make will have the same text size.<br />
<img src='http://blog.anonrandomname.com/wp-content/uploads/2008/01/image1.png' alt='Increased text size using rc params' /></p>
<p>Until, that is, I reset to the defaults:</p>
<pre class = "prettyprint"><code class = "code">p.rcdefaults()</code></pre>
<p>The result is this:<br />
<img src='http://blog.anonrandomname.com/wp-content/uploads/2008/01/image2.png' alt='reset to the default params' /></p>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/adjust-settings-for-matplotlib-using-rc-and-matplotlibrc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Change distance of tick labels from axis</title>
		<link>http://scienceoss.com/change-distance-of-tick-labels-from-axis/</link>
		<comments>http://scienceoss.com/change-distance-of-tick-labels-from-axis/#comments</comments>
		<pubDate>Thu, 17 Jan 2008 15:42:01 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[plotting]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[axis]]></category>
		<category><![CDATA[pylab]]></category>
		<category><![CDATA[tick labels]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=63</guid>
		<description><![CDATA[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(&#8216;xtick.major), pad=10) When you&#8217;re done and want to reset the rc settings, use p.rcdefaults() See matplotlibrc for more settings you can change via [...]]]></description>
			<content:encoded><![CDATA[<p>Set the rc parameters using the <span class="c">rc</span> function.</p>
<pre class = "prettyprint"><code class = "code">
import pylab as p
p.rc(('xtick.major','xtick.minor','ytick.major','ytick.minor'), pad=10)
p.plot([1,2,3])
</code></pre>
<p>If you only want to change one of the tick labels, say, the x major ticks, use<br />
p.rc(&#8216;xtick.major), pad=10)</p>
<p>When you&#8217;re done and want to reset the rc settings, use</p>
<pre class = "prettyprint"><code class = "code">p.rcdefaults()</code></pre>
<p>See matplotlibrc for more settings you can change via the <code>rc</code> command.</p>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/change-distance-of-tick-labels-from-axis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Interacting with figures in Python</title>
		<link>http://scienceoss.com/interacting-with-figures-in-python/</link>
		<comments>http://scienceoss.com/interacting-with-figures-in-python/#comments</comments>
		<pubDate>Thu, 17 Jan 2008 15:09:16 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[plotting]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[ginput]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=62</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>Here is some code from the matplotlib mailing list, sent by Rob Hetland, for selecting points from a plot.</p>
<pre class = "prettyprint"><code class = "code">
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()
</code></pre>
<pre class = "prettyprint"><code class = "code">
#!/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)) &#038;&#038; (y(n)<yp(j))) ||
                 	 ((yp(j)<=y(n)) &#038;&#038; (y(n)<yp(i)))) &#038;&#038;
                	(x(n) < (xp(j) - xp(i)) * (y(n) - yp(i)) / (yp(j) - yp(i)) + xp(i)))

    	    	c = !c;
        	}
    	out(n) = c;
        }
        """
        weave.inline(code, ['xp','yp','x','y','out'],
                     type_converters=weave.converters.blitz)
        return out
except:
    # if scipy.weave is not available, use pure python routine.  Slow.
    def npnpoly(verts, points):
        """Check whether given points are in the polygon.

        points - Nx2 array

        See http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
        """
        out = []

        xpi = verts[:,0]
        ypi = verts[:,1]
        # shift
        xpj = xpi[np.arange(xpi.size)-1]
        ypj = ypi[np.arange(ypi.size)-1]
        maybe = np.empty(len(xpi),dtype=bool)
        for x,y in points:
            maybe[:] = ((ypi <= y) &#038; (y < ypj)) | ((ypj <= y) &#038; (y < ypi))
            out.append(sum(x < (xpj[maybe]-xpi[maybe])*(y - ypi[maybe]) \
                           / (ypj[maybe] - ypi[maybe]) + xpi[maybe]) % 2)

        return np.asarray(out,dtype=bool)

class Polygeom(np.ndarray):
    """
    Polygeom -- Polygon geometry class
    """

    def __new__(self, verts):
        """
        Given xp and yp (both 1D arrays or sequences), create a new polygon.

        p = Polygon(vertices) where vertices is an Nx2 array

        p.inside(x, y) - Calculate whether points lie inside the polygon.
        p.area() - The area enclosed by the polygon.
        p.centroid() - The centroid of the polygon
        """
        verts = np.atleast_2d(verts)

        assert verts.shape[1] == 2, 'Vertices should be an Nx2 array, but is %s' % str(verts.shape)
        assert len(verts) >= 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()
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/interacting-with-figures-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Timezones in Python</title>
		<link>http://scienceoss.com/timezones-in-python/</link>
		<comments>http://scienceoss.com/timezones-in-python/#comments</comments>
		<pubDate>Thu, 10 Jan 2008 18:24:06 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[daylight savings]]></category>
		<category><![CDATA[eastern]]></category>
		<category><![CDATA[timezone]]></category>
		<category><![CDATA[tz]]></category>
		<category><![CDATA[utc]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=59</guid>
		<description><![CDATA[I had a Python datetime object, T. I knew it was in Eastern time and wanted to convert to UTC. I also wanted it to keep track of daylight savings time, for when I have dates later in the year. Python datetime objects have &#8220;support&#8221; for timezone info, but you have to implement it yourself. [...]]]></description>
			<content:encoded><![CDATA[<ul>
<li>I had a Python datetime object, <span class="c">T</span>.</li>
<li>I knew it was in Eastern time and wanted to convert to UTC.  </li>
<li>I also wanted it to keep track of daylight savings time, for when I have dates later in the year.</li>
<li>Python datetime objects have &#8220;support&#8221; for timezone info, but you have to implement it yourself.  Read: more coding overhead that I&#8217;m trying to avoid.
</ul>
<p>Here&#8217;s how to do it the easy way.<span id="more-59"></span></p>
<p>There&#8217;s a module called <a href="http://pytz.sourceforge.net/">pytz</a> to make things easy.</p>
<h3>Import</h3>
<p>First, import the goodies.</p>
<pre class = "prettyprint"><code class = "code">from pytz import timezone
import pytz
import datetime
</code></pre>
<h3>Create timezone objects</h3>
<p>Then, create two <span class="c">timezone</span> objects: one for eastern time, and one for utc.</p>
<pre class = "prettyprint"><code class = "code">eastern_tz = timezone('US/Eastern')
utc_tz = pytz.utc
</code></pre>
<h3>Localize the time</h3>
<p>Next, &#8220;localize&#8221; the time, T.  This is a way of telling the datetime object what timezone it should be.</p>
<pre class = "prettyprint"><code class = "code">T = datetime.datetime(2008, 1, 10, 7, 20, 46, 613195)
eastern_datetime = eastern_tz.localize(T)
    # datetime.datetime(2008, 1, 10, 7, 20, 46, 613195,
    # tzinfo=<dstTzInfo 'US/Eastern' EST-1 day, 19:00:00 STD>)
</code></pre>
<h3>Convert the localized time</h3>
<p>Now convert <span class="c">eastern_datetime</span> into UTC using its <span class="c">astimezone</span> method.  Feed it the utc_tz timezone object to tell it how to convert.</p>
<pre class = "prettyprint"><code class = "code">utc_datetime = eastern_datetime.astimezone(utc_tz)
</code></pre>
<h2>Plotting time series with timezones</h2>
<p>The documentation for matplotlib says you can give plot_date() a string like &#8216;US/Eastern&#8217; for the tz keyword.  This didn&#8217;t work for me; I got errors.</p>
<pre class = "prettyprint"><code class = "code"><type 'exceptions.TypeError'>: astimezone() argument 1 must be datetime.tzinfo, not str
WARNING: Failure executing file: <sun_to_db.py></code></pre>
<p>To fix this, I found my matplotlibrc file (the Linux command <span class="c">locate matplotlibrc</span> gave me the file <span class="c">/usr/lib/python2.5/site-packages/matplotlib/mpl-data/matplotlibrc</span>) and changed the timezone to &#8220;US/Eastern&#8221;.</p>
<p>date2num converts dates into number of days (fraction part represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC.</p>
<p>But plot_date pulls from matplotlibrc file to determine which timezone to show in.</p>
<p>That means, if you have a list of datetime objects that are in fact Eastern, you have to make sure they are converted via pytz, then date2num&#8217;d, then plotted.</p>
<p>You&#8217;ll also need to set the xdata formatter ax.fmt_xdata = DateFormatter(&#8216;%x %H:%M %Z&#8217;)</p>
<p>In sum, assume you have a list of datetime objects that are really in Eastern time.  This list is called timeline.</p>
<pre class = "prettyprint"><code class = "code">timeline # a list of datetime objects that are really in Eastern
values # a list of values, one for each time in timeline
import pytz
from pytz import timezone
from pylab import figure, show, DateFormatter

eastern = timezone('US/Eastern')
utc = pytz.utc
timeline_eastern = [eastern.localize(i) for i in timeline]
timeline_utc = [i.astimezone(utc) for i in timeline_eastern]

# Both of these are the same! Why? Cause date2num is smart and
# keeps track of timezones.  Nevertheless, these are both in "days from
# 0001-01-01 00:00 UTC"
mpl_dates_1 = [date2num(i) for i in timeline_eastern]
mpl_dates_2 = [date2num(i) for i in timeline_utc]

fig = figure()
ax = fig.add_subplot(111)
ax.plot_date(timeline,values)

# This formats numbers in the lower right to be proper dates
# that change when you mouse over the plot.
ax.fmt_xdata = DateFormatter('%x %H:%M %Z')

show()

</code></pre>
<p>The coolest part is if you plot a list of dates year round, the timezones change appropriately between EDT and EST!</p>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/timezones-in-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Create a second y-axis in matplotlib</title>
		<link>http://scienceoss.com/create-a-second-y-axis-in-matplotlib/</link>
		<comments>http://scienceoss.com/create-a-second-y-axis-in-matplotlib/#comments</comments>
		<pubDate>Sun, 02 Dec 2007 16:48:36 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[axis]]></category>
		<category><![CDATA[plot]]></category>
		<category><![CDATA[pylab]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[subplot]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=30</guid>
		<description><![CDATA[Today I was trying to figure out how to plot two time series with differently scaled values. I found two_scales.py example in the matplotlib examples which describes how to do it. Here&#8217;s a slightly simplified version of the code, and afterward a detailed explanation of what&#8217;s going on. from pylab import * x = [1,2,3,4,5] [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was trying to figure out how to plot two time series with differently scaled values.  I found  <a href="http://matplotlib.sourceforge.net/examples/two_scales.py">two_scales.py</a> example in the matplotlib examples which describes how to do it.</p>
<p>Here&#8217;s a slightly simplified version of the code, and afterward a detailed explanation of what&#8217;s going on.<span id="more-30"></span></p>
<pre class = "prettyprint"><code class = "code">
from pylab import *

x = [1,2,3,4,5]
y1 = [10,25,30,45,50]
y2 = [1,3,4,7,12]

ax1 = subplot(111)

plot(x, y1, 'b-')

ax2 = twinx()

plot(x, y2, 'r--')
show()</code></pre>
<h2>Step-by-step explanation.</h2>
<p>Basically, we make two separate axes right on top of each other.  The data in y1 will go on the first created axes, and y2 will go on the second created axes.  The key to this is the twinx() function.  What it does is explained below.<br />
<img style="border:1px dashed; padding:10px;float:left;margin:10px;" src='http://blog.anonrandomname.com/wp-content/uploads/2007/12/text3610.png' alt='two axes code explanation 01' /><br />
<br style="clear:both"/><br />
<img class="codeExample" src='http://blog.anonrandomname.com/wp-content/uploads/2007/12/two_axes1.png' alt='two axes code explanation 03' /><br />
<br style="clear:both;"/><br />
<img class="codeExample" src='http://blog.anonrandomname.com/wp-content/uploads/2007/12/two_axes2.png' alt='two axes code explanation 04' /><br />
What&#8217;s happening here? <span class="c">twinx()</span> duplicates the current set of axes (the current set of axes is ax1).  The source code of <span class="c">twinx()</span> has a line like this:</p>
<pre class="prettyprint"><code class = "code">ax2 = gcf().add_axes(ax1.get_position(), sharex=ax1, frameon=False)</code></pre>
<p>Which:</p>
<ul>
<li>adds a new set of axes to the current figure (that&#8217;s the <span class="c">gcf()</span> part).</li>
<li>puts the new set of axes in the same position as <span class="c">ax1</span> (that&#8217;s the <span class="c">ax1.get_position()</span> part)</li>
<li>makes the new set of axes have an x axis with the same properties as the first axes, <span class="c">ax1</span>.  When you pan or zoom the figure both axes will move together.</li>
<li>returns the new axis
</ul>
<p>The result is a new set of axes right on top of the old one, ready and primed for some plotting.</p>
<p>The rest of the code plots a red dashed line in the new axes using the data in <span class="c">y2</span>, and the <span class="c">show()</span> command shows your handiwork.<br />
*not really magic</p>
<h2>Final product</h2>
<p><a href='http://blog.anonrandomname.com/wp-content/uploads/2007/12/two-axes.png' title='two y axes example'><img src='http://blog.anonrandomname.com/wp-content/uploads/2007/12/two-axes.png' alt='two y axes example' /></a></p>
<h2>Oh no! I forgot to label the axes!</h2>
<p>The nice thing about saving the axes as ax1 and ax2 is that you can change either one of them at any time.  Just call any one of the 280 possibilities (In IPython, type ax1, then a &#8220;.&#8221;, then the tab key &#8212; that is, ax1.[TAB] &#8212; for a list of what axes can do).</p>
<p>For example, you can use the set_ylabel() method of each axes object.</p>
<pre class = "prettyprint"><code class = "code">
ax1.set_ylabel('first y-axis')
ax2.set_yabel('second y-axis')
</code></pre>
<p>If you have already used show(), then your changes WON&#8217;T immediately be updated.  This is by design, in case you are adding many things to a figure and don&#8217;t want to refresh after every little thing you add.  Once you&#8217;re ready to redraw the figure, Use</p>
<pre class = "prettyprint"><code class = "code">draw()</code></pre>
<p>You can label the x axis too, but you&#8217;ll only need to choose either <span class="c">ax1.set_xlabel(&#8216;x label here&#8217;)</span> or <span class="c">ax2.set_xlabel(&#8216;x label here&#8217;)</span>.  You can remove an axis label by just setting it to an empty string: ax2.set_xlabel(&#8221;).</p>
<p>With labels, it looks something like this:<br />
<img src='http://blog.anonrandomname.com/wp-content/uploads/2007/12/labeled-two-axes.png' alt='two y axes with axis labels' /></p>
<h2>More than two y-axes?</h2>
<p>Unfortunately, this is not yet implemented in matplotlib but it&#8217;s on the wishlist, as <a href="http://sourceforge.net/mailarchive/message.php?msg_id=42E2C619-976C-4E19-870B-5A590D44FC31%40llnl.gov">this post</a> describes, along with a suggestion to use PyX instead of matplotlib for a graph of this type.</p>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/create-a-second-y-axis-in-matplotlib/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating a custom bar plot in matplotlib</title>
		<link>http://scienceoss.com/bar-plot-with-custom-axis-labels/</link>
		<comments>http://scienceoss.com/bar-plot-with-custom-axis-labels/#comments</comments>
		<pubDate>Sun, 04 Nov 2007 04:27:32 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[matplotlib]]></category>
		<category><![CDATA[bar]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[plot]]></category>
		<category><![CDATA[pylab]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=18</guid>
		<description><![CDATA[Bar plots are one of the simplest kinds of plots, but for some reason in many programs it&#8217;s difficult to get the labels you want, correct error bars, and control over every aspect of the plot. Here&#8217;s how to create a custom bar plot using the Python plotting module matplotlib. Fire up IPython and matplotlib. [...]]]></description>
			<content:encoded><![CDATA[<p>Bar plots are one of the simplest kinds of plots, but for some reason in many programs it&#8217;s difficult to get the labels you want, correct error bars, and control over every aspect of the plot.  Here&#8217;s how to create a custom bar plot using the Python plotting module matplotlib.<span id="more-18"></span></p>
<p>Fire up <a href="http://ipython.scipy.org/moin/">IPython</a> and <a href="http://matplotlib.sourceforge.net/">matplotlib</a>.</p>
<h2>plain ol&#8217; bar plot</h2>
<pre class="brush: python; title: ; notranslate">

# pylab contains matplotlib plus other goodies.
import pylab as p

#make a new figure
fig = p.figure()

# make a new axis on that figure. Syntax for add_subplot() is
# number of rows of subplots, number of columns, and the
# which subplot. So this says one row, one column, first
# subplot -- the simplest setup you can get.
# See later examples for more.

ax = fig.add_subplot(1,1,1)

# your data here:

x = [1,2,3]
y = [4,6,3]

# add a bar plot to the axis, ax.
ax.bar(x,y)

# after you're all done with plotting commands, show the plot.
p.show()
</pre>
<p>Here&#8217;s what it looks like:<br />
<a href="http://scienceoss.com/wp-content/uploads/2007/11/simple-barplot.png"><img src="http://scienceoss.com/wp-content/uploads/2007/11/simple-barplot-300x226.png" alt="" title="simple-barplot" width="300" height="226" class="aligncenter size-medium wp-image-322" /></a></p>
<p>This is just the basic bar plot.  Not that great for publication . . . it needs better colors, some labels, and maybe some error bars.  The scripts below walk you through doing just that.</p>
<h2>barplot-2.py</h2>
<p>Now let&#8217;s tweak it out a little . . .  this time we&#8217;ll make two subplots, one with the same plotting commands as above, and the other subplot with red, thinner bars.</p>
<pre class="brush: python; title: ; notranslate">
import pylab as p

fig = p.figure()

# Here we're adding 2 subplots.  The grid is set
# up as one row, two columns.
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

x = [1,2,3]
y = [4,6,3]

# first axis, with the same bar plot as before.
ax1.bar(x,y)

# on the second axis, make the width smaller (default is 0.8)
ax2.bar(x,y,width=0.3, facecolor='red')
ax2.set_ylabel('number of widgets')

p.show()
</pre>
<p>And the result:<br />
<a href="http://scienceoss.com/wp-content/uploads/2007/11/barplot-2.png"><img src="http://scienceoss.com/wp-content/uploads/2007/11/barplot-2-300x226.png" alt="" title="barplot-2" width="300" height="226" class="aligncenter size-medium wp-image-323" /></a></p>
<h2>barplot-3.py</h2>
<p>OK, time to make it look nicer.  This code may look like it&#8217;s long, but it&#8217;s mostly a bunch of comments explaining what everything does.</p>
<p><strong>Added 1/28/07:</strong><br />
By the way, <a href="http://blog.anonrandomname.com/2008/01/27/errorbars-in-matplotlib/">here</a> are my notes for using errorbars in general with matplotlib.</p>
<pre class="brush: python; title: ; notranslate">
import pylab as p
fig = p.figure()
ax = fig.add_subplot(1,1,1)

# note the change: I'm only supplying y data.
y = [4, 6, 7, 3, 5]

# Calculate how many bars there will be
N = len(y)

# Generate a list of numbers, from 0 to N
# This will serve as the (arbitrary) x-axis, which
# we will then re-label manually.
ind = range(N)

# I'm also supplying (fake) error for each y value.
# You can use numpy's standard deviation, numpy.std(data)
# to calculate error bars for your own data.
# Standard error is standard deviation over sqrt(N),
# so you could use numpy.std(x)/numpy.sqrt(len(x))
# to get standard error for the data in a list x.
err = [1.2, 1.5, 2.5, 1.2, 2.0]

# See note below on the breakdown of this command
ax.bar(ind, y, facecolor='#777777',
       align='center', yerr=err, ecolor='black')

#Create a y label
ax.set_ylabel('Counts')

# Create a title, in italics
ax.set_title('Counts, by group',fontstyle='italic')

# This sets the ticks on the x axis to be exactly where we put
# the center of the bars.
ax.set_xticks(ind)

# Labels for the ticks on the x axis.  It needs to be the same length
# as y (one label for each bar)
group_labels = ['control', 'cold treatment',
                 'hot treatment', 'another treatment',
                 'the last one']

# Set the x tick labels to the group_labels defined above.
ax.set_xticklabels(group_labels)

# Extremely nice function to auto-rotate the x axis labels.
# It was made for dates (hence the name) but it works
# for any long x tick labels
fig.autofmt_xdate()

p.show()
</pre>
<p>Here&#8217;s what the result looks like:<br />
<a href="http://scienceoss.com/wp-content/uploads/2007/11/barplot-3.png"><img src="http://scienceoss.com/wp-content/uploads/2007/11/barplot-3-300x226.png" alt="" title="barplot-3" width="300" height="226" class="aligncenter size-medium wp-image-324" /></a></p>
<p>Note: Here&#8217;s the breakdown of the command used above, </p>
<pre class="brush: python; title: ; notranslate">
ax.bar(ind, y, facecolor='#777777',
       align='center', yerr=err, ecolor='black')
</pre>
<p>:</p>
<ul>
<li><code>ind</code> contains the x values to plot</li>
<li><code>y</code> contains the y values to plot</li>
<li>the <code>#777777 </code>is the <a href="http://en.wikipedia.org/wiki/Hex_color">hexadecimal color code</a> for a dark gray</li>
<li><code>align</code> tells the bar command to align the bars on the <code>center</code> of the x values we give it, instead of aligning the left side of the bar (which is the default)</li>
<li><code>yerr</code> specifies the error bars in the y direction.</li>
<li><code>ecolor</code> is the color of the error bars</li>
</ul>
</blockquote>
<p>By the way, here&#8217;s the un-commented, more compact version of the same exact code:</p>
<pre class="brush: python; title: ; notranslate">
import pylab as p
fig = p.figure()
ax = fig.add_subplot(1,1,1)
y = [4, 6, 7, 3, 5]
N = len(y)
ind = range(N)
err = [1.2, 1.5, 2.5, 1.2, 2.0]
ax.bar(ind, y, facecolor='#777777',
       align='center', yerr=err, ecolor='black')
ax.set_ylabel('Counts')
ax.set_title('Counts, by group',fontstyle='italic')
ax.set_xticks(ind)
group_labels = ['control', 'cold treatment',
                     'hot treatment', 'another treatment',
                     'the last one']
ax.set_xticklabels(group_labels)
fig.autofmt_xdate()
p.show()
</pre>
<h2>So what else can you tweak?</h2>
<p>Just about everything.  Below is the help entry for the bar function, which you can view in IPython by typing <code>p.ax.bar?</code>  or <code>p.bar?</code>.  Note, for example, that you can change things like the transparency of the bars, give each bar different widths, change the edge colors, change the size of the &#8216;caps&#8217; on the error bars, and so on.</p>
<pre class="brush: plain; title: ; notranslate">
bar(left, height, width=0.8, bottom=0,
        color=None, edgecolor=None, linewidth=None,
        yerr=None, xerr=None, ecolor=None, capsize=3,
        align='edge', orientation='vertical', log=False)
    Make a bar plot with rectangles bounded by
      left, left+width, bottom, bottom+height
            (left, right, bottom and top edges)
    left, height, width, and bottom can be either scalars or sequences
    Return value is a list of Rectangle patch instances
        left - the x coordinates of the left sides of the bars
        height - the heights of the bars
    Optional arguments:
        width - the widths of the bars
        bottom - the y coordinates of the bottom edges of the bars
        color - the colors of the bars
        edgecolor - the colors of the bar edges
        linewidth - width of bar edges; None means use default
            linewidth; 0 means don't draw edges.
        xerr and yerr, if not None, will be used to generate errorbars
        on the bar chart
        ecolor specifies the color of any errorbar
        capsize (default 3) determines the length in points of the error
        bar caps
        align = 'edge' (default) | 'center'
        orientation = 'vertical' | 'horizontal'
        log = False | True - False (default) leaves the orientation
                axis as-is; True sets it to log scale
    For vertical bars, align='edge' aligns bars by their left edges in
    left, while 'center' interprets these values as the x coordinates of
    the bar centers. For horizontal bars, 'edge' aligns bars by their
    bottom edges in bottom, while 'center' interprets these values as the
    y coordinates of the bar centers.
    The optional arguments color, edgecolor, linewidth, xerr, and yerr can
    be either scalars or sequences of length equal to the number of bars.
    This enables you to use bar as the basis for stacked bar charts, or
    candlestick plots.
    Optional kwargs:
            alpha: float
            animated: [True | False]
            antialiased or aa: [True | False]
            axes: an axes instance
            clip_box: a matplotlib.transform.Bbox instance
            clip_on: [True | False]
            clip_path: an agg.path_storage instance
            edgecolor or ec: any matplotlib color
            facecolor or fc: any matplotlib color
            figure: a matplotlib.figure.Figure instance
            fill: [True | False]
            hatch: unknown
            label: any string
            linewidth or lw: float
            lod: [True | False]
            picker: [None|float|boolean|callable]
            transform: a matplotlib.transform transformation instance
            visible: [True | False]
            zorder: any number

    Addition kwargs: hold = [True|False] overrides default hold state&lt;/code&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/bar-plot-with-custom-axis-labels/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>

