Using Pythons matplotlib

I had a look at the python 2D plotting library matplotlib. For more information about this library, you might want to have a look at the corresponding Wikipedia article.

I’m looking for a way to make simple plots from x,y value pairs and it seems that matplotlib is the way to go in Python environments. Let’s have a look at an example. The following script will save a simple bar plot to a PNG file. Nothing fancy, just something to have a starting point.

import matplotlib.pyplot as plt
import numpy as np

data = (1, 2, 3, 4, 5)
pos = np.arange(len(data)), data)
plt.xticks(pos+0.4, data)

If you have matplotlib correctly installed in your Python environment, it will generate the following bar plot in a PNG file called “bar.png” in the current directory.

Simple bar plot
Simple bar plot

Please not that the script generates just the plot, not the subtitle. While you can do this in matplotlib, I have added the subtitle here in HTML for simplicity.  I have decided to have a further look at matplotlib. It looks promising and I would like to use it inside a simple web application. Let’s see how far this goes.

Using Pythons matplotlib

JSON in Python and Common Lisp

Both, Python and Common Lisp have libraries for writing and reading JSON format. JSON can be used as an alternative to XML, when not only machines will read the data. XML can be hard to read when you have more tags than data. JSON does not have the overhead of start and end tags.

In Python, you can import module json from the Python standard library.

>>> import json
>>> a = [1, 2, 3]
>>> json.dumps(a)
‘[1, 2, 3]’
>>> json.loads(‘[1, 2, 3]’)
[1, 2, 3]

In Common Lisp, you can use the CL-JSON library.

CL-USER> (ql:quickload “CL-JSON”)
CL-USER> (cl-json:encode-json ‘(1 2 3))
CL-USER> (with-input-from-string (s “[1, 2, 3]”) (cl-json:decode-json s))
(1 2 3)

These are just very simple examples, but you see that usage is straightforward. If you don’t like the syntax of JSON, you might want to have a look at YAML. JSON is a subset of YAML version 1.2.

JSON in Python and Common Lisp

How do I write and read plain text files in Python?

Writing and reading plain text files is easy in Python. Look at the following functions.

def write_file(txt, filename):
    with open(filename, ‘w’) as f:

def read_file(filename):
    with open(filename, ‘r’) as f:

def test_text_io():
    txt = ‘text’
    write_file(txt, ‘spam.txt’)
    s = read_file(‘spam.txt’)
    print s

IF you define the functions and then call test_text_io(), it should create a file called ‘spam.txt’ in your current working directory and print ‘text’ in your console.

How do I write and read plain text files in Python?