Python code to draw cos(x) using matplotlib

Let’s draw again. This time we will use a matplotlib and numpy to get python cos(x) graph.

cosine(x) plot

Draw a cos(x)

I have prepared a code which I am pasting below.

You need to import both matplotlib and numpy.

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
x_min = -5.0
x_max = 5.0
y_min = -1.5
y_max = 1.5
x = np.arange(x_min, x_max, 0.10)
y = np.cos(x)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.plot(x, y)
grid_x_ticks_minor = np.arange(x_min, x_max, 0.25 )
grid_x_ticks_major = np.arange(x_min, x_max, 0.50 )
ax.set_xticks(grid_x_ticks_minor, minor = True)
grid_y_ticks_minor = np.arange(y_min, y_max, 0.5)
grid_y_ticks_major = np.arange(y_min, y_max, 1.0)
ax.set_yticks(grid_y_ticks_minor, minor = True)
ax.grid(True, which='minor', alpha=0.25, color = 'b')


This code first imports matplotlib and numpy. Then, it creates a figure and an axes object. The axes object is used to plot the data.

See also  Here's how to draw a hyperbola

The code specifies the x and y-axis limits with xlim and ylim, ensuring the full range of the cosine function is displayed.

The code then plots the x and y values using the plot function.

The code incorporates both minor and major grid lines using set_xticks and set_yticks for enhanced readability.

The code then sets the title of the plot and displays it.

See also  How to calculate mode in Python?