<?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; pylab</title>
	<atom:link href="http://scienceoss.com/tags/pylab/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.1</generator>
		<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>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>

