MatPlot Library

In this section we will look at how to plot series using Matplot Library.

Let’s suppose that we have a series with the following value : 200,400,600,800,800.

Those values relates to the month 2 (Feb), 4 (Apr), 6 (June), 8 (Aug) and 10 (Oct)

We want to represent the series using MatPlot.

Below the code that we have to write:

import matplotlib.pyplot as plt
plt.plot([2,4,6,8,10],[200,400,600,800,800])
plt.xlabel("Months")
plt.ylabel("Spent USD")
plt.title("Representing a Series of Data")
plt.show()

As you can see we define a plot which will contain the X and Y respectively

We can set the label using the command plt.xlabel(“some text”) or pltylabel(“some text”).

If we want to add a tile the command to use is plt.title(“Add your title here”)

Finally we show the plot with the command plt.show()

Ok we have plotted a line but what happens if we need to plot more lines and we need to put a legend and we want to format the lines in a different manner?

Let’s have a look at a more complicated example

import matplotlib.pyplot as plt

plt.plot([2,4,6,8,10],[200,250,300,400,550],'b--',label="Revenue")
plt.xlabel("Months")
plt.ylabel("Units Sold")
plt.plot([2,4,6,8,10],[150,200,210,260,360],'r:',label="Cost")

plt.title("Representing a Series of Data")
plt.legend(loc="best")
plt.show()

As you can see now we have two lines and a legend providing more information.

In comparison with the previous graph we have

  1. Added a sencond line
  2. Format the data choosing a different color for each line
  3. Chose a different style for each line

To format the line we have used a format string. Here is the link to the MatPlot WebPage which contains very useful information

Link


Leave a Reply

Your email address will not be published. Required fields are marked *