Plotting with ‘matplotlib’

What is ‘matplotlib’? It’s a Python package which can be used to plot everything from a simple parabola or sine wave right up to complex statistical data. Of course, I use it just to print interesting curves, like the one above. I’ll discuss the program I wrote below.

Since it is a Python package it helps if you know how to write Python programs, but I don’t dive too deep into Python. Anyway, the above curves were printed by a program that is only eleven lines long!

At the top of the Python code, we need to tell it to use ‘matplotlib’ and I’ve included a line to tell the code that we need to use the ‘numpy’ maths package. Here’s the first bit of the program:

import matplotlib.pyplot as plt  # This is the plotting library
import numpy as np               # A common Python package

Plotting something involves matching one set of data against another. Commonly these sets of data are named ‘x’ and ‘y’, but they can have any names that the plotter desires. The relevant code in this program is as follows:

max_range = 1000
x = np.linspace(-2*np.pi, 2*np.pi, max_range)
y = np.sin(x)

The line that starts ‘x =’ uses the numpy ‘linspace’ routine to generate a numpy array of one thousand (max_range) elements evenly spaced between -2 time pi and 2 times pi. The line that starts ‘y =’ then creates another numpy array, taking the individual elements of the array x, applying the numpy sine function and appending the result to the end of the array y.

In the earliest version of this program, I created the two numpy arrays by means of a loop, but by creating numpy arrays using this method, I can do it in two lines. Like all good ideas I got it from someone else’s program on the Internet. There is only one program, the old joke goes, and that is the “Hello World!” program, and all other programs are descendants of that single archetype.

OK, so, I created two more arrays using the same technique, and here are the two lines of code:

z = np.sin(2*x)
zz = np.sin(4*x)

So, I could have drawn three plots, one for each array, but that wouldn’t have been that interesting, so I decide to plot the sum of all three arrays (against the x array), and also the product of all three arrays (again, against the x array). Numpy arrays make this easy.

# y = np.sin(x) * np.sin(2*x) * np.sin(4*x)
plt.plot(x, y * z * zz, label='product')
# y = np.sin(x) + np.sin(2*x) + np.sin(4*x)
plt.plot(x, y + z + zz, label='sum')

The ‘plot’ statements each draw a line in the final figure, and generate a label for the line. The comments describe the curve in an x/y format, in a simple mathematical style .

The final couple of lines (see below) are needed to show the labels and the complete figure. Below is the whole Python program, comments and all.

import matplotlib.pyplot as plt
import numpy as np

# Basic Figures
# sine wave
max_range = 1000
x = np.linspace(-2*np.pi, 2*np.pi, max_range)
y = np.sin(x)

# sine wave, freq * 2
# x = np.linspace(-2*np.pi, 2*np.pi, max_range)
z = np.sin(2*x)
zz = np.sin(4*x)

# y = np.sin(x) * np.sin(2*x) * np.sin(4*x)
plt.plot(x, y * z * zz, label='product')
# y = np.sin(x) + np.sin(2*x) + np.sin(4*x)
plt.plot(x, y + z + zz, label='sum')

plt.legend()
plt.show()

To close the post, I’m going present a more complex example. This one combines the plots described above, with a separate subplot of the three waves that were used to create the first subplot. At the very end is the source code.

import matplotlib.pyplot as plt
import numpy as np

# Basic Figures
# sine wave
max_range = 1000

fig, (ax1, ax2) = plt.subplots(2, 1)

# The x array runs from -2*pi to +2*pi
x = np.linspace(-2*np.pi, 2*np.pi, max_range)

# One component of the final plot
y = np.sin(x)

# sine wave, freq * 2
z = np.sin(2*x)
# Freq * 4
zz = np.sin(4*x)import matplotlib.pyplot as plt
import numpy as np

# Basic Figures
# sine wave
max_range = 1000

fig, (ax1, ax2) = plt.subplots(2, 1)

# The x array runs from -2*pi to +2*pi
x = np.linspace(-2*np.pi, 2*np.pi, max_range)

# One component of the final plot
y = np.sin(x)

# sine wave, freq * 2
z = np.sin(2*x)
# Freq * 4
zz = np.sin(4*x)
ax1.plot(x, y, label='sin(x)')
ax1.plot(x, z, label='sin(2*x)')
ax1.plot(x, zz, label='sin(4*x)')

legend1 = ax1.legend()

# y = sin(x) * sin(2x) * sin(4x)
ax2.plot(x, y * z * zz, label='product')
# y = sin(x) + sin(2x) + sin(4x)
ax2.plot(x, y + z + zz, label='sum')

legend2 = ax2.legend()

plt.show()
ax1.plot(x, y, label='sin(x)')
ax1.plot(x, z, label='sin(2*x)')
ax1.plot(x, zz, label='sin(4*x)')

legend1 = ax1.legend()

# y = sin(x) * sin(2x) * sin(4x)
ax2.plot(x, y * z * zz, label='product')
# y = sin(x) + sin(2x) + sin(4x)
ax2.plot(x, y + z + zz, label='sum')

legend2 = ax2.legend()

plt.show()

A Can of Worms

The Writer at Work
The Writer at Work

This is yet another post about the writing process. OK, it fascinates me, as I consider what happens in my brain/mind as I write something, but I risk the possibility of it not being interesting to anyone else. It’s around 1500 words long, which is a bit longer than my usual posts.

So, the conventional view of the writing process is that it is a linear process. The writer sits down at his or her desk, starts furiously writing, casting off page after page, until with a final flourish he types or writes “The End” and the deed is done.

The real process is much more dynamic than that, at least for me. The following is a brief description of what happened when I wrote a story that I have written about in previous posts. I haven’t included any elements of the story because I want to concentrate on the process.

The End
The End

In a previous post, I wrote about a story that, as I wrote it, became too long for the competition in which I wanted to enter it. When I had completed it, I modified it and shortened it. However I wasn’t happy with the result, so I abandoned it, and started again from scratch, cutting and pasting bits from the original now and then.

This worked fine and I submitted the story into the competition. However, I now had three versions of the same story, and one of them, the original short one, was significantly different from the other two. A core topic in the story had changed, and the motivation of the main character was consequently different. There were other things about that version that I didn’t like so I considered consigning it to the bit bucket. However (fortunately) I didn’t do that right away.

I was happy with the version that I submitted for the competition, but I felt that the longer version could be improved. With no limit on the length, I could be more descriptive, go into the characters a bit more and draw out their motivations and fill in their back stories. I could also pull in bits from the short version which did work, and also ideas from the competition version that weren’t in the longer version.

Merging three stories into one
Merging three stories into one

I hope that I’ve given some idea of how complex this was. I was effectively merging three versions into one, and some bits didn’t fit together too well. I was constantly revising the longer one so that the timeline and the events fitted together properly with the bits I was getting from the other two versions. Normally things don’t get as complex as this for me!

After I got a consistent story, I developed it further. I’d add a paragraph or two to bring out the motivation of some character or other, and as a result one or two of the minor characters blossomed into being more than minor characters.

Initially the main character and his wife were a bit aloof, but I decided to make them more sociable, more friendly. The wife mostly dropped out of the main story, but returns for a major cameo. Another major character developed to become almost the equal of the protagonist, and a minor character emerged from the shadows to become a more rounded character.

The Protagonist
The Protagonist, but not of my story! It’s actually the goddess, Nike.

By this stage my story was complete in the longer version, and, because I had effectively gutted and abandoned the original shortened version I deleted it, as mentioned above. So now I had two versions, the shorter competition version and the longer version.

Now, when I’ve written a story, and although it is in a sense complete, I don’t leave it there. I read it through, again and again, constantly revising and modifying it. I don’t usually change the story that much, but I go after spelling errors, grammatical errors, continuity errors, and so on. In every run through I change something. Maybe just the way that I said something. The position of a word in a sentence. Maybe a name, a location, a motivation. I could keep editing probably for ever. I never write “The End”.

My main point here is that, using modern technology, I have been able to, basically, rewrite the story twice and extend and revise the original story dramatically.

Juliet's Balcony
A balcony in Verona which has nothing to do with Romeo and Juliet, but still gets visited and photographed by tourists who think it has.

I wonder how ancient writers did it. I can’t imagine Shakespeare turning out multiple drafts of his plays. For one thing, he did it by hand. To create a new draft, he would have to write out the whole thing again with the changes. The decision to change the name of a character from “Fred” to “Mercutio” wouldn’t be taken lightly. For another thing, paper was, relatively speaking, expensive in those days. Printing was expensive.

Once he had written the play, it would be printed, but only a few copies would be produced. The printed copies were not intended for general reading, but were intended as “prompt books” for use in a theatre. This means, of course, that each printing might be different.

Old Books
Old books. I imagine that Shakespeare’s plays would have been printed in books like this.

I’ve not heard of Shakespeare making notes or outlines of his plays, but maybe he did. Maybe somewhere there is Shakespeare’s hand a scrap of paper that says something like “R sees J on blcny. J doesn’t see R. R calls J, J calls guards. R thrown out.” But we know that the final version doesn’t run that way!

I conclude that Shakespeare probably had the whole play mapped out in his mind, or at least great parts of it, including the words that he invented, the sentence construction, the characters and the plot. It’s an awesome feat if he did do it that way. The idea of juggling all those characters and scenes in his head, developing the story, and finally getting it down on paper in an almost final version is amazing.

Well, I wrote that before actually wondering if there was anything on the Internet about how Shakespeare wrote his plays. The answer is fascinating, at least to me! It seems that Shakespeare and his fellow playwrights of the era cooperated extensively with each other, adding bits to each other’s plays. So Shakespeare’s plays were, in part, written by others! Interestingly, that’s very similar to the way that TV shows are written today, I understand.

An author at work
An author at work

We have the luxury, these days to dash off a story (or a play or whatever) and not worry too much about the details. We can fix those on the second go through! Electrons are as cheap as chips. I could have edited the bit about Shakespeare above, but I wanted to demonstrate how I was thinking, since this is post is about my thought processes when I write things.

So, I’d say the my writing style is like opening a can of worms. Who knows in what direction they are going to wriggle? Who knows where they are going to take us? I have a strong feeling that when I write a story, I’m only nominally in charge. The characters seem to have a life of their own, and they have their own needs and desires. They interact in way that I would not have predicted when I started writing their story and often the story changes as I write it. I’m often interested in how it is going to turn out.

That’s how I write. But others do it differently. Some, even in this electronic era write things out by hand. Others use mechanical typewriters and a few swear by old, really old, versions of software.

Mechanical typewriter
Mechanical typewriter

Things are different from Shakespeare’s day in many ways. It is more usual to write novels, rather than plays, and books are cheap and widely available. Writers do not, as a general rule, cooperate, as in Shakespeare’s day. A book will perused by an editor and checked by a proof reader many times before it is printed, and may be revised many times.

Even for those who write things by hand have the advantage of paper being cheap and readily available. They, and those who use mechanical typewriters, can easily rewrite a page and slot it into the manuscript fairly easily.

If you read the advice out there on how to write, you would sometimes think that the bare essentials are a well developed plot and well defined characters. I’ve read advice to that effect many times, but there are people who advocate the “just start writing” approach, and that is, as you can see above, my preference. I would not like to be straitjacketed by a rigid plot and static characters.

Inspiration?
Inspiration?

But some people prefer that approach and good luck to them! And there are those in the middle. Those who might have plot in mind or a set of characters, but aren’t about to spend time in developing the plot or the characters in detail. That’s maybe most writers.

Whatever approach you prefer, it is a good idea to research how to write. How to structure a story, how to develop characters and so on. It’s silly to think that all you need to do is pick up a pen and write, and you will produce a best seller. Even the best writers didn’t do that. They wrote at home and at school as kids, and they will have read voraciously, in all sorts of genres, and they may have actually formally studied literature. They will have practised extensively. And that’s what I am doing, and continue to do. Studying and practising. It’s one of the reasons for this blog!

Editing the first draft
Editing the first draft. That’s not me. I would be doing it directly on the computer!