A graph reveals a pattern that a table hides. Python draws graphs with the Matplotlib library, whose pyplot module is imported as plt. The same steps are used for almost every graph.

Basic Steps for a Plot

The program first imports the module with import matplotlib.pyplot as plt. It then prepares the data, usually as lists or NumPy arrays, and draws it with plt.plot(x, y). Labels are added with plt.xlabel() and plt.ylabel(), a heading with plt.title(), and a key with plt.legend(). Finally plt.show() displays the graph, or plt.savefig("name.png") stores it in a file.

Definition: Matplotlib. A Python library for drawing two-dimensional and simple three-dimensional graphs from data.

Line Plot

A line plot joins the points (x, y) in order and is suited to a trend over time. Style options can be given in plot(), such as color, linestyle, linewidth and marker. The code below draws the monthly profit of a company with the required axis labels.

Table 4.3: Common pyplot functions

Function Purpose Example
plot(x, y) Line plot plt.plot(m, p)
xlabel, ylabel Axis labels plt.xlabel("Month Number")
title Heading plt.title("Profit")
legend Key for lines plt.legend()
show Display graph plt.show()
import matplotlib.pyplot as plt
month = [1, 2, 3, 4, 5, 6]
profit = [20, 24, 22, 30, 35, 41]
plt.plot(month, profit, marker="o")
plt.xlabel("Month Number")
plt.ylabel("Total profit")
plt.title("Profit of company ABC")
plt.show()

Sine and Cosine Curves

To draw a smooth curve, many x values are generated with np.linspace(start, stop, number), and the function is applied to the whole array at once. Plotting np.sin(x) and np.cos(x) on the same axes with a label for each gives the familiar waves. Both repeat every 2 pi and lie between -1 and +1, and the cosine curve is the sine curve shifted to the left by a quarter of a cycle. Polynomial and exponential curves are drawn the same way, for example y = x ** 2 and y = np.exp(x).

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.legend()
plt.show()

Example 4.3: Values of a curve

Problem: Find the values of sin x and cos x at x = 0, pi / 2 and pi, which are the points used when drawing the curves.

Solution:

  1. Create the array of the three x values with NumPy.
  2. Apply np.sin and np.cos to the whole array and round the results.

Result: sin is 0, 1, 0 and cos is 1, 0, -1 at the three points.

import numpy as np
x = np.array([0, np.pi / 2, np.pi])
print(np.round(np.sin(x), 3), np.round(np.cos(x), 3))
print(np.linspace(0, 1, 5))

Output

[0. 1. 0.] [ 1.  0. -1.]
[0.   0.25 0.5  0.75 1.  ]

Common mistakes

  • Forgetting plt.show(), so no graph appears in a script.
  • Using too few points for a curve, which makes it look jagged.
  • Leaving out axis labels and a title, so the graph cannot be understood.

Key takeaways

  • import matplotlib.pyplot as plt is the standard import.
  • plt.plot draws a line, and xlabel and ylabel name the axes.
  • np.linspace creates evenly spaced x values.
  • plt.show displays the graph and plt.savefig saves it.

Practice questions

  1. Which function draws a line plot?
  2. Which function creates evenly spaced values for a smooth curve?
  3. What is the range of the sine function?

Answers to the practice questions

  1. plt.plot().
  2. np.linspace().
  3. Between -1 and +1.

Sources

  • Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit IV