SaltyCrane Blog — Notes on JavaScript and web development

How to draw a simple line using python and the matplotlib API -

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...


""" line_ex.py                                             
"""
from matplotlib.figure import Figure
from matplotlib.axes import Axes
from matplotlib.lines import Line2D
from matplotlib.backends.backend_agg import FigureCanvasAgg

fig = Figure(figsize=[4,4])
ax = Axes(fig, [.1,.1,.8,.8])
fig.add_axes(ax)
l = Line2D([0,1],[0,1])
ax.add_line(l)

canvas = FigureCanvasAgg(fig)
canvas.print_figure("line_ex.png")

Comments


#1 Francesco commented on :

It gave me headache but, if I am not wrong, figure have to be created in this way

fig = Figure(figsize=(4, 4))

rather than

fig = Figure(figsize=[4, 4])

(I changed square with round brackets)

Nice post btw. ~fb