<?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; plotting</title>
	<atom:link href="http://scienceoss.com/categories/plotting/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>Change properties of ggplot plots</title>
		<link>http://scienceoss.com/change-properties-of-ggplot-plots/</link>
		<comments>http://scienceoss.com/change-properties-of-ggplot-plots/#comments</comments>
		<pubDate>Mon, 04 Feb 2008 16:28:54 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[plotting]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[ggplot]]></category>
		<category><![CDATA[grayscale]]></category>
		<category><![CDATA[parameters]]></category>

		<guid isPermaLink="false">http://scienceoss.com/change-properties-of-ggplot-plots/</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>Try </p>
<pre class="prettyprint"><code class="code">?ggopt</code></pre>
<p>to see the different ways of adjusting plot background, axes, aspect ratio, border colors, and strip labels.</p>
<h3>Change the font size of the labels.</h3>
<p>This acts on the currently active plot.</p>
<pre class="prettyprint"><code class="code">grid.gedit('label', gp=gpar(fontsize=16))</code></pre>
<p>Or just change one type of label (here, the yaxis).</p>
<pre class="prettyprint"><code class="code">grid.gedit(gPath("yaxis", "labels"), gp=gpar(col="red"))</code></pre>
<h3>Use a black and white theme</h3>
<p>The newest version of ggplot2 (0.5.7) allows you to have black and white themes.</p>
<pre class="prettyprint"><code class="code">pl = ggplot(diamonds)+aes(x=carat, y=price) +
    geom_point()+theme_bw
pl
</code></pre>
<p>I like to tweak the <span class="c">theme_bw</span> a little before using it as above:</p>
<pre class="prettyprint"><code class="code">theme_bw$grid.colour = "grey80"
theme_bw$border.colour = "gray70"</code></pre>
<h3>Change the strip labels</h3>
<pre class="prettyprint"><code class="code">pl$strip.gp = gpar(fill="grey90")
pl$strip.txt.gp = gpar(col="black", fontsize=16)
pl</code></pre>
<h3>Change factor colors to grayscale</h3>
<pre class="prettyprint"><code class="code">pl+scale_colour_grey(end=0.7,start=0,name='')
pl</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/change-properties-of-ggplot-plots/feed/</wfw:commentRss>
		<slash:comments>0</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>
	</channel>
</rss>

