Write a Python program to plot the function y = x2 using the pyplot or matplotlib
libraries.
Answers
Plotting graph with matplotlib
We want to plot the function with Python. We will be using the numpy and matplotlib libraries.
We start with importing them:
The most basic syntax for matplotlib.pyplot.plot() is:
We can customize marker and line style and color with other options, but we do not need them here.
We now need the arrays for x and y.
We use numpy's linspace function.
The function creates a numpy array of n equally-spaced points from start to end.
We just use -10 and 10 as start and end points here. They can be changed as required.
Then, we can simply use list comprehension to create the list for y.
Finally, the function displays the graph.
The Code
import numpy as np
import matplotlib.pyplot as plt
# Create numpy array for x
x = np.linspace(-10, 10, 100)
# Create list of y = x^2 using list comprehension
y = [i*i for i in x]
# Plot
plt.plot(x, y)
plt.show()
Answer:
import NumPy as np
import matplotlib.pyplot as plt
# Create NumPy array for x
x = np.linspace(-10, 10, 100)
# Create a list of y = x^2 using list comprehension
y = [i*i for i in x]
# Plot
plt.plot(x, y)
plt.show()
Explanation:
Matplotlib is a Python charting library that consists of a collection of command-style methods that allow it to behave similarly to MATLAB. It provides an object-oriented API for leveraging general-purpose GUI toolkits to integrate charts into programmes. Each #pyplot# function modifies the figures in some way, such as by producing a figure, a plot area in the figure, charting some lines in the plot area, decorating the plot with labels, and so on.
#SPJ3