How to Create a Graph in Python

publicité
14/02/2011
How to Create a Graph in Python - The…
Logilab Spécialiste de Python et du Libre pour l'informatique scientifique www.logilab.fr
Talend: ETL Open Source Téléchargement 100% gratuit : ETL open source toute source de données download.Talend.com/O
Ellexus Breeze Advanced Script Debugging Linux build tracing for any flow! www.ellexus.com
How to Create a Graph in Python
Monday, 19 July 2010 21:14
Garret Staus
[Report This
Article]
(0 votes, average 0 out of 5)
Python is an increasingly versatile language, and is frequently used for quickly writing up computation based programs. It can be
useful to graph input, and thankfully Python has one of the most convenient and accessible libraries to graph objects - Matplotlib.
Matplotlib is a plotting library for Python which extends the numpy library. Using matplotlib we can quickly create a graph of any
two lists. It is a very powerful library capable of making many types of graphs, including (but not limited to) bar graphs, scatter
plots, log graphs, and histograms. This tutorial will teach you how to very quickly make a graph in matplotlib. Note that matplotlib
is a very powerful library and this is just a scratch of the surface!
1. First, you will need to install matplotlib if you do not already have it. The matplotlib installation page provides a pretty
comprehensive and easy walkthrough on installing matplotlib (and numpy if you do not already have it).
http://matplotlib.sourceforge.net/users/installing.html
2. Now we're ready to write some code. Begin by setting up a new figure in matplotlib, making sure to import the library. We'll
also set up the "backend" of Matplotlib so we will be able to save the figure to our desired output.
1
import matplotlib.pyplot as plt
2
3
plt.figure()
3. Calling the figure() method sets up a new figure for our current plot. Depending on what kind of graph we want, we will call
a different method. Almost all graph types are called with two parameters for the x series and the y series, which are
simply lists in Python. Since most graphs are simple scatter plots, we will look at an example using plot(). In the example
below, we declare each series statically. Typically, one list will be some computation of the x_series. To add multiple lines
to a graph, simply call plot() again. If you want to create a new graph, call figure() again.
4
5
6
7
#create some data
x_series = [0,1,2,3,4,5]
y_series_1 = [x**2 for x in x_series]
y_series_2 = [x**3 for x in x_series]
8
9
10
#plot the two lines
11
plt.plot(x_series, y_series_2)
plt.plot(x_series, y_series_1)
4. Now we have plotted some data to our figure. But how do we see it? The most practical way is to save it to a .PDF or .PNG.
8
plt.savefig("example.png")
5. Open the file you just saved to see your graph!
thetechrepo.com/…/465-how-to-creat…
1/4
14/02/2011
How to Create a Graph in Python - The…
Adding Labels and Axis Limits
Of course, the graph above is accurate but it's not exactly useful. Often times we want to want add labels and a title, change the
axes, etc. Here we will cover some of the most common things that can be added to a graph. Let's re-visit the code from the first
part and add some fun stuff.
1
#add in labels and title
2
3
4
plt.xlabel("Small X Interval")
plt.ylabel("Calculated Data")
plt.title("Our Fantastic Graph")
5
6
7
#add limits to the x and y axis
8
9
10
11
plt.xlim(0, 6)
plt.ylim(-5, 80)
#add legend
plt.legend()
#save figure
plt.savefig("example.pdf")
Most of these functions are pretty self-explanatory and won't be explained in any more depth here. Now let's look at our graph:
thetechrepo.com/…/465-how-to-creat…
2/4
14/02/2011
How to Create a Graph in Python - The…
Adding a Legend and Modifying Line Properties
When we are plotting multiple lines (or whatever type of graph you are plotting), it is often necessary to be able to distinguish the
lines. We can add labels to each line after we plot it, and then add a legend to the graph. Here is an example:
1
2
3
plt.plot(x_series, y_series_1, label="x^2")
plt.plot(x_series, y_series_2, label="x^3")
4
plt.legend(loc="upper left")
Putting It All Together
This tutorial has covered the very basics of how to create a graph in Python. Browse The Tech Repo for more in-depth tutorials
concerning Matplotlib. Let's look at a final version of the code and the graph it creates.
1
2
3
4
#set up matplotlib and the figure
5
6
7
#create data
8
9
10
import matplotlib.pyplot as plt
plt.figure
x_series = [0,1,2,3,4,5]
y_series_1 = [x**2 for x in x_series]
y_series_2 = [x**3 for x in x_series]
#plot data
11
12
13
plt.plot(x_series, y_series_1, label="x^2")
plt.plot(x_series, y_series_2, label="x^3")
14
15
16
#add in labels and title
17
18
19
20
plt.title("Our Fantastic Graph")
21
22
23
plt.xlabel("Small X Interval")
plt.ylabel("Calculated Data")
#add limits to the x and y axis
plt.xlim(0, 6)
plt.ylim(-5, 80)
#create legend
24
25
26
plt.legend(loc="upper left")
27
plt.savefig("example.png")
#save figure to png
thetechrepo.com/…/465-how-to-creat…
3/4
14/02/2011
How to Create a Graph in Python - The…
PARTNER LINKS:
CITATIONS:
http://matplotlib.sourceforge.net/index.html
Last Updated on Monday, 19 July 2010 22:08
RELATED ARTICLES
» Setup DSL to work with Linksys WRT54g or other router
So you have your DSL modem from AT&T, SBC Global, TDS, or other provider working on your PC directly and you want to set it
up to work with your router (Linksys WRT54g / WRT54gl or other router) instead and can't find straight forward instructions on
how to do this right? Following these simple steps, we should be able to get your internet up and running through your router
with relative ease. The following steps are written for AT&T and a WRT54gl router, but should be...
Read more...
» How to Install an Updated Driver For NVIDIA Graphics Cards
» How to Use gprof (The Basics)
thetechrepo.com/…/465-how-to-creat…
4/4
Téléchargement
Explore flashcards