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

