Let’s draw again. This time we will use a matplotlib and numpy to get python cos(x) graph.
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.
The code then sets the x and y limits of the plot. This ensures that the entire cosine function is visible.
The code then plots the x and y values using the `plt.plot()` function.
The code then adds minor and major grid lines to the plot. This makes the plot easier to read.
The code then sets the title of the plot and displays it.
Key Takeaways
* To draw the cosine function using matplotlib, you need to import the `matplotlib.pyplot` and `numpy` libraries.
* You can create a figure and an axes object using the `plt.figure()` and `plt.subplot()` functions.
* You can set the x and y limits of the plot using the `plt.xlim()` and `plt.ylim()` functions.
* You can plot the x and y values using the `plt.plot()` function.
* You can add minor and major grid lines to the plot using the `plt.grid()` function.
* You can set the title of the plot using the `plt.title()` function.
* You can display the plot using the `plt.show()` function.
FAQ
* **Q: What is the difference between minor and major grid lines?**
A: Minor grid lines are used to make the plot easier to read. They are usually lighter and less prominent than major grid lines.
* **Q: How can I change the color of the grid lines?**
A: You can change the color of the grid lines using the `color` argument of the `plt.grid()` function.
* **Q: How can I change the thickness of the grid lines?**
A: You can change the thickness of the grid lines using the `linewidth` argument of the `plt.grid()` function.
* **Q: How can I change the style of the grid lines?**
A: You can change the style of the grid lines using the `linestyle` argument of the `plt.grid()` function.