Computer Science, asked by chandudevarakonda1, 1 year ago

Write a Python program to plot the function y = x2 using the pyplot or matplotlib
libraries.

Answers

Answered by QGP
3

Plotting graph with matplotlib

We want to plot the y=x^2 function with Python. We will be using the numpy and matplotlib libraries.

We start with importing them:

\texttt{import numpy as np } \\ \texttt{import matplotlib.pyplot as plt}

The most basic syntax for matplotlib.pyplot.plot() is:

\texttt{plt.plot(x-array, y-array)}

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 \texttt{np.linspace(start, end, n)} 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.

\texttt{x = np.linspace(-10, 10, 100)} \\ \texttt{y = [i*i for i in x]}

Finally, the \texttt{plt.show()} function displays the graph.

 \rule{300}{1}

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()

Attachments:
Answered by dayanidhisharma19
0

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

Similar questions