Python matplotlib – 1

In this article:

  1. A simple graphic with pyplot
  2. Using lists for graphic coordinates
  3. A graphic with many lines
  4. Using tuples for graphic coordinates
  5. What happen when lists or tuples for coordinates have different size?
  6. Save graphic in a file

1. A simple graphic with pyplot

Most simple graphic with matplotlib is plotting with pyplot interface:

import matplotlib.pyplot as myplot
myplot.plot([1, 5], [2, 12])
myplot.show()

This show graphic like below:

Simple graphic with mathplotlib pyplot.

From image result that pyplot draw a line between two points (1,2) and (5,12)

2. Using lists for graphic coordinates

Arguments for “plot” in myplot.plot([1, 5], [2, 12]) are 2 lists:
l1 = [1, 5]
l2 = [2, 12]

The same graphic is obtained using:

import matplotlib.pyplot as myplot
l1 = [1, 5]
l2 = [2, 12]
myplot.plot(l1, l2)
myplot.show()

In this case line draw is between
point 1 with coordinates:
x=first element of list l1, or l1[0]
y=first element of list l2, or l2[0]
point 2 with coordinates:
x=second element of list l1, or l1[1]
y=second element of list l2, or l2[1]

3. A graphic with many lines

If lists l1 and l2 have more elements, plot will draw line(es) between appropriate points. For example:

import matplotlib.pyplot as myplot
l1 = [1, 3, 5]
l2 = [2, 4, 12]
myplot.plot(l1, l2)
myplot.show()

Code will draw:

A pyplot graphic with many lines

In this case lines are between points that have coordinates:
(1,2), (3,4), (5,12)
or
(l1[0],l2[0]), (l1[0],l2[0]), (l1[0],l2[0])

4. Using tuples for graphic coordinates

The same graphic is obtained if we use tuples, i.e. code:

import matplotlib.pyplot as myplot
t1 = (1, 3, 5)
t2 = (2, 4, 12)
myplot.plot(t1, t2)
myplot.show()

Lists or tuples can have more elements, it is important that those to have
the same number of elements.

5. What happen when lists or tuples for coordinates have different size?

If we try with different elements, for example code:

import matplotlib.pyplot as myplot
l1 = [1, 3, 5]
l2 = [2, 4, 7, 12]
myplot.plot(l1, l2)
myplot.show()

this will fail with error:
ValueError: x and y must have same first dimension, but have shapes (3,) and (4,)

6. Save graphic in a file

Command myplot.show() display effectively resulted graphic.
Using savefig() graphic is saved in a file for example:

import matplotlib.pyplot as myplot
l1 = [1, 3, 5]
l2 = [2, 4, 12]
myplot.plot(l1, l2)
myplot.savefig(“C:\tmp\fig1.png”)

Here savefig method is used with only one parameter, the file path.
Method savefig have many more parameters, like here.
Above code will save graphic in file C:\tmp\fig1.png