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)
ax.set_xticks(grid_x_ticks_major)
 
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.set_yticks(grid_y_ticks_major)
 
ax.grid(True, which='minor', alpha=0.25, color = 'b')

plt.title('cosine(x)')
plt.show()

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  How to resolve ValueError: operands could not be broadcast together with shapes

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  Draw random stars using turtle