SaltyCrane: matplotlibhttps://www.saltycrane.com/blog/2011-12-08T10:35:43-08:00Creating a histogram plot with python
2011-12-08T10:35:43-08:00https://www.saltycrane.com/blog/2011/12/creating-histogram-plot-python/<pre class="python">from matplotlib import pyplot
filename = 'times_1201.txt'
lines = open(filename).readlines()
x = [int(line.strip()) for line in lines]
bins = [i * 1000 for i in range(10)]
pyplot.hist(x, bins=bins, facecolor='green', alpha=0.75)
pyplot.xlabel('Time (ms)')
pyplot.ylabel('Count')
pyplot.suptitle(r'Sup title')
pyplot.title(r'Title')
pyplot.grid(True)
pyplot.savefig(filename + '.png')</pre>
How to draw a simple line using python and the matplotlib API -
2007-01-05T18:08:00-08:00https://www.saltycrane.com/blog/2007/01/how-to-draw-simple-line-using-python_05/
<div><font face="Arial" color="#000080" size="2"><span style="FONT-SIZE: 12px; COLOR: black; FONT-FAMILY: times">I'm continuing to learn the low level object oriented matplotlib API. My goal is to create very customizable, perfect plots. Here is how to draw a simple line. First create a figure that is 4 inches by 4 inches. Then create some axes with a 10% margin around each edge. Then add the axes to the figure. Then create a line from (0,0) to (1,1). Then add the line to the axes. Then create a canvase. Then create the .png file. Looks like good object oriented python fun to me... </span><br /><br /><br /></font><pre style="FONT-SIZE: 12px; COLOR: black">""" line_ex.py <br /> """ <br /> from matplotlib.figure import Figure <br /> from matplotlib.axes import Axes <br /> from matplotlib.lines import Line2D <br /> from matplotlib.backends.backend_agg import FigureCanvasAgg<br /> <br /> fig = Figure(figsize=[4,4]) <br /> ax = Axes(fig, [.1,.1,.8,.8]) <br /> fig.add_axes(ax) <br /> l = Line2D([0,1],[0,1]) <br /> ax.add_line(l) <br /> <br /> canvas = FigureCanvasAgg(fig) <br /> canvas.print_figure("line_ex.png") <br /> </pre></div>
How to use the pylab API vs. the matplotlib API
2007-01-04T16:59:00-08:00https://www.saltycrane.com/blog/2007/01/how-to-use-pylab-api-vs-matplotlib-api_3134/
<div><a href="http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html">This article</a> has a good description of the 2 API's in matplotlib: the pylab API and the matplotlib API. I've been using the pylab interface because it is easier, especially coming from a matlab background. But I wanted to get direct access to the matplotlib classes so I needed to use the matplotlib API. Here is a simple example that creates a .png figure using the 2 different API's. <br /><br />Here is the example using the pylab API: <pre>""" api_pylab.py <br /> """ <br /> from pylab import * <br /> <br /> figure(figsize=[4,4]) <br /> axes([.1,.1,.8,.8]) <br /> scatter([1,2],[3,4]) <br /> savefig('api_pylab.png') <br /> </pre><br />Here is the example using the matplotlib API: <pre>""" api_matplotlib.py <br /> """ <br /> from matplotlib.figure import Figure <br /> from matplotlib.backends.backend_agg import FigureCanvasAgg <br /> <br /> fig = Figure(figsize=[4,4]) <br /> ax = fig.add_axes([.1,.1,.8,.8]) <br /> ax.scatter([1,2], [3,4]) <br /> canvas = FigureCanvasAgg(fig) <br /> canvas.print_figure("api_matplotlib.png") <br /> </pre></div>
How to create some derived arrow classes with matplotlib and python
2007-01-03T10:41:00-08:00https://www.saltycrane.com/blog/2007/01/how-to-create-some-derived-arrow_03/
<div>Here is an example of how to create some derived arrow classes with matplotlib and python. The arrow() function <span class="260423818-03012007">in </span>matplotlib accepts origin and delta x and delta y inputs. I changed this to polor coordinates so Arrow2 accepts the x and y coordinates of the origin, the length, and the angle. Then I created 4 classes derived from Arrow2 called ArrowRight, ArrowLeft, ArrowUp, and ArrowDown. These just set the angle for you to 0, 180, 90, and 270 respectively.<span class="260423818-03012007"> Notice too that the **kwargs can be passed down so you can still set all the other parameters.</span>
<pre>""" arrow_ex2.py """
from pylab import *
def main():
figure()
axes()
Arrow2(.5,.5,.2,45)
ArrowRight(.5,.5,.2)
ArrowLeft(.5,.5,.2)
ArrowUp(.5,.5,.2)
ArrowDown(.5,.5,.2)
show()
class Arrow2:
def __init__(self, x0, y0, length, angle=0.0, color='k', width=0.01, **kwargs):
dx = length*cos(angle*pi/180)
dy = length*sin(angle*pi/180)
arrow (x0, y0, dx, dy,
width=width,
edgecolor=color,
facecolor=color,
antialiased=True,
head_width=5*width,
head_length=7.5*width,
**kwargs)
class ArrowRight(Arrow2):
def __init__(self, x0, y0, length, **kwargs):
Arrow2.__init__(self, x0, y0, length, angle=0.0, **kwargs)
class ArrowLeft(Arrow2):
def __init__(self, x0, y0, length, **kwargs):
Arrow2.__init__(self, x0, y0, length, angle=180.0, **kwargs)
class ArrowUp(Arrow2):
def __init__(self, x0, y0, length, **kwargs):
Arrow2.__init__(self, x0, y0, length, angle=90.0, **kwargs)
class ArrowDown(Arrow2):
def __init__(self, x0, y0, length, **kwargs):
Arrow2.__init__(self, x0, y0, length, angle=270.0, **kwargs)
if __name__ == "__main__":
main() </pre>
</div>
How to draw an arrow with matplotlib and python
2007-01-02T14:21:00-08:00https://www.saltycrane.com/blog/2007/01/how-to-draw-arrow-with-matplotlib-and/
Here is an example of how to draw an arrow with matplotlib. It should be<br />very easy, but I had to change the width setting so the arrow head would<br />not be too small. Further documentation is here:<br /><a href="http://matplotlib.sourceforge.net/matplotlib.pylab.html#-arrow">http://matplotlib.sourceforge.net/matplotlib.pylab.html#-arrow</a><p>""" arrow_ex.py<br />"""<br />from pylab import *<br />figure()<br />axes()<br />arrow(.1,.1,.2,.2, width=0.01)<br />show()
</p>
Example pie charts using python and matplotlib
2006-12-19T10:33:00-08:00https://www.saltycrane.com/blog/2006/12/example-pie-charts-using-python-and/
<span style="font-size:85%;"><a href="http://bp3.blogger.com/_lZhqNsiakm4/RYhnZj7vbNI/AAAAAAAAAAM/jLR2mx7Jx4M/s1600-h/utilization_web.png"><img id="BLOGGER_PHOTO_ID_5010368274289880274" style="" alt="" src="http://bp3.blogger.com/_lZhqNsiakm4/RYhnZj7vbNI/AAAAAAAAAAM/jLR2mx7Jx4M/s320/utilization_web.png" border="0" /></a></span><br />
I needed to make some pie charts and didn't like the results I got from Excel. It was too hard to customize the plots exactly the way I wanted them. I have used Matlab before and I preferred Matlab to Excel. However, Python is my favorite thing to use so I searched for python and matlab on Google and found matplotlib. Matplotlib is a matlab-like plotting library for Python. You can get matplotlib from <a href="http://matplotlib.sourceforge.net/">http://matplotlib.sourceforge.net/</a>, but it is also bundled with the Enthought version of Python so I got it from there. Update: I realized that the Enthought bundle didn't include the latest version of matplotlib so I installed the latest version of matplotlib and the required NumPy as well.<br />
<br />
Step-by-step:<br />
1. Download enthought version of Python 2.4.3 from <a href="http://code.enthought.com/enthon/">http://code.enthought.com/enthon/</a> (Click on the "enthon-python2.4-1.0.0.exe" link is at the bottom of the page) and install it.<br />
2. Download "numpy-1.0.1.win32-py2.4.exe" from <a href="http://sourceforge.net/project/showfiles.php?group_id=1369">http://sourceforge.net/project/showfiles.php?group_id=1369</a> and install it.<br />
3. Download "matplotlib-0.87.7.win32-py2.4.exe" from <a href="http://sourceforge.net/projects/matplotlib">http://sourceforge.net/projects/matplotlib</a> and install it.<br />
3. Open a text editor and type this inside:<br />
<pre class="python">
#!/usr/bin/env python
"""
http://matplotlib.sf.net/matplotlib.pylab.html#-pie for the docstring.
"""
from pylab import *
# create figure
figwidth = 10.0 # inches
figheight = 3.5 # inches
figure(1, figsize=(figwidth, figheight))
rcParams['font.size'] = 12.0
rcParams['axes.titlesize'] = 16.0
rcParams['xtick.labelsize'] = 12.0
rcParams['legend.fontsize'] = 12.0
explode=(0.05, 0.0)
colors=('b','g')
Ncols = 3
plotheight = figwidth/Ncols
H = plotheight/figheight
W = 1.0 / Ncols
margin = 0.1
left = [W*margin, W*(1+margin), W*(2+margin)]
bottom = H*margin
width = W*(1-2*margin)
height = H*(1-2*margin)
# cpu utilization
utilized = 10.0
free = 100.0 - utilized
fracs = [utilized, free]
axes([left[0], bottom, width, height])
patches = pie(fracs, colors=colors, explode=explode, autopct='%1.f%%', shadow=True)
title('CPU Throughput')
legend((patches[0], patches[2]), ('Processing', 'Idle'), loc=(0,-.05))
# ROM utilization
utilized = 30.0
free = 100.0 - utilized
fracs = [utilized, free]
axes([left[1], bottom, width, height])
patches = pie(fracs, colors=colors, explode=explode, autopct='%1.f%%', shadow=True)
title('ROM Memory Usage')
legend((patches[0], patches[2]), ('Used', 'Unused'), loc=(0,-.05))
# RAM utilization
utilized = 15.0
free = 100.0 - utilized
fracs = [utilized, free]
axes([left[2], bottom, width, height])
patches = pie(fracs, colors=colors, explode=explode, autopct='%1.f%%', shadow=True)
title('RAM Memory Usage')
legend((patches[0], patches[2]), ('Used', 'Unused'), loc=(0,-.05))
savefig('utilization')
show()
</pre>
4. Save the file as piechart.py in c:\temp<br />
5. In Windows, go to Start -> All Programs -> Python 2.4 (Enthought Edition) -> IPython Shell<br />
6. Type in "cd c:\temp"<br />
7. Type "run piechart.py" and hit enter<br /><span style="font-family:arial; font-size:50%; color:black;">Technorati tags: <a href="http://technorati.com/tag/python" rel="tag">python</a>, <a href="http://technorati.com/tag/matplotlib" rel="tag">matplotlib</a>, <a href="http://technorati.com/tag/piechart" rel="tag">piechart</a></span>