The Wayback Machine - https://web.archive.org/web/20241006202544/https://www.geeksforgeeks.org/matplotlib-pyplot-plot-function-in-python/
Open In App

Matplotlib.pyplot.plot() function in Python

Last Updated : 29 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Matplotlib is a powerful Python library that serves as a numerical and mathematical extension for the NumPy library. One of its key components is Pyplot, which offers a state-based interface to the Matplotlib module, presenting users with a familiar MATLAB-like environment. Through Matplotlib.pyplot.plot() function in Python, users can effortlessly create a variety of plots, including Line Plots, Contour Plots, Histograms, Scatter Plots, 3D Plots, and more. This versatility makes Matplotlib an invaluable tool for data visualization and analysis in the Python programming language.

What is Matplotlib.pyplot.plot() Function?

The matplotlib.pyplot.plot() function is a fundamental component of the Matplotlib library, specifically within the Pyplot module. It serves the purpose of generating a 2D hexagonal binning plot based on the given data points represented by the variables x and y. It connects data points with lines, allowing customization of the plot’s appearance through parameters such as line styles and markers. This versatile function is widely used for data visualization in various domains.

Syntax: matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)

  • Parameters:
    • x, y: These parameters represent the horizontal and vertical coordinates of the data points. The ‘x’ values are optional, allowing flexibility in the plotting process.
    • fmt: This is an optional parameter that contains a string value. It is used to specify the format of the plot, defining the line style, marker, and color.
    • data: An optional parameter, ‘data’ refers to an object with labeled data. It provides a convenient way to pass data directly, enhancing the readability and ease of use.
  • Returns: The plot() function returns a list of Line2D objects, each representing a segment of the plotted data. These Line2D objects encapsulate the characteristics and attributes of the plotted lines, allowing for further customization and analysis.

Matplotlib.pyplot.plot() Function in Python

There are various way of creating plot using Matplotlib.pyplot.plot() function in Python, Their are some examples illustrate the matplotlib.pyplot.plot() function in matplotlib.pyplot:

  • Basic Line Plot
  • Multiple Lines Plot
  • Scatter Plot with Multiple Markers
  • Two Curves Plot

Line Plots in Matplotlib

By importing Matplotlib’s plot() we created a line plot with data [1, 2, 3]. The title() function sets the plot title, draw() updates the plot, and show() displays it, providing a basic illustration of Matplotlib for data visualization in Python.

Python3




import matplotlib.pyplot as plt
import numpy as np
 
# Plotting a simple line graph
plt.plot([1, 2, 3])
 
# Setting the title
plt.title('Matplotlib Line Plot Example')
 
# Updating and displaying the plot
plt.draw()
plt.show()


Output:

first

Basic Line Plot

Multiple Lines Using Matplotlib

By importing Matplotlib to plot sine and cosine functions on the same graph. It generates data, sets styles for each function, adds labels and a title, displays a legend, and then shows the plot, illustrating the sine and cosine curves.

Python3




import matplotlib.pyplot as plt
import numpy as np
 
# Generate data
x = np.linspace(0, 2*np.pi, 100)
y1, y2 = np.sin(x), np.cos(x)
 
# Plotting multiple lines on a single plot
plt.plot(x, y1, label='Sin(x)', color='b')
plt.plot(x, y2, label='Cos(x)', color='r', linestyle='--')
 
# Adding labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Multiple Lines Plot')
 
# Displaying the legend and the plot
plt.legend()
plt.show()


Output

second

Multiple Lines Plot

Markers in Matplotlib

By importing Matplotlib we generated a customized scatter plot with 50 random data points, featuring red circular markers. It includes axis labels, a title (‘Scatter Plot Example’), and a legend. The show() function displays the plot, demonstrating a basic example of data visualization with Matplotlib in Python.

Python3




import matplotlib.pyplot as plt
import numpy as np
 
# Generate random data
np.random.seed(42)
x = np.random.rand(50)
y = np.random.rand(50)
 
# Plotting a scatter plot with custom markers
plt.plot(x, y, marker='o', linestyle='', markersize=8, color='r', label='Scatter Plot')
 
# Adding labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Example')
 
# Displaying the legend
plt.legend()
 
# Display the plot
plt.show()


Output:

3

Scatter Plot with Multiple Markers

Plotting Multiple Curves

By importing Matplotlib we created a line plot with two curves: a blue curve (y=x^2) and an orange curve (y=1−x^3). The data is generated randomly, sorted for smooth curves, and plotted with the plot() function. The plot is limited to the range [0, 1] on both axes, showcasing a visual representation of mathematical functions.

Python3




# Implementation of matplotlib function
   
import matplotlib.pyplot as plt
import numpy as np
   
# Fixing random state for reproducibility
np.random.seed(19680801)
   
# create random data
xdata = np.random.random([2, 10])
   
# split the data into two parts
xdata1 = xdata[0, :]
xdata2 = xdata[1, :]
   
# sort the data so it makes clean curves
xdata1.sort()
xdata2.sort()
   
# create some y data points
ydata1 = xdata1 ** 2
ydata2 = 1 - xdata2 ** 3
   
# plot the data
plt.plot(xdata1, ydata1, color ='tab:blue')
plt.plot(xdata2, ydata2, color ='tab:orange')
   
   
# set the limits
plt.xlim([0, 1])
plt.ylim([0, 1])
 
plt.title('matplotlib.pyplot.plot() example 2')
   
# display the plot
plt.show()


Output

last

Two Curves Plot

Conclusion

In conclusion, the matplotlib.pyplot.plot() function in Python is a fundamental tool for creating a variety of 2D plots, including line plots, scatter plots, and more. Its versatility allows users to customize plots by specifying data points, line styles, markers, and colors. With optional parameters such as ‘fmt’ and ‘data,’ the function provides flexibility in plot formatting and data handling. Additionally, the returned Line2D objects allow for further manipulation and analysis of the plotted data. Overall, Matplotlib’s plot() function is a key component in the realm of data visualization, offering a user-friendly interface for creating insightful and visually appealing plots in Python.



Similar Reads

Matplotlib.pyplot.figimage() function in Python
Matplotlib is a widely used library in Python for plotting various graphs, as it provides very efficient ways and easy to understand methods for complex plots also. pyplot is a collection of command style functions that make matplotlib work like MATLAB. figimage() function matplotlib.pyplot.figimage() is a method for adding a non-resampled image to
2 min read
Matplotlib.pyplot.hexbin() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. Matplotlib.pyplot.hexbin() function The hexbi
2 min read
Matplotlib.pyplot.suptitle() function in Python
Matplotlib is a library in Python and it is a mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.suptitle() Function The suptitle() function in pyplot module of the matplotlib library is used to add a title to the figure. Syntax: matplotlib.pyp
3 min read
Matplotlib.pyplot.xscale() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. matplotlib.pyplot.xscale() function The xscal
2 min read
Matplotlib.pyplot.setp() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. Matplotlib.pyplot.setp() function The setp()
2 min read
matplotlib.pyplot.semilogy() function in Python
Matplotlib is the most popular and Python-ready package that is used for visualizing the data. We use matplotlib for plotting high-quality charts, graphs, and figures. matplotlib.pyplot.semilogy() Function The matplotlib.pyplot.semilogy() function in pyplot module of matplotlib library is used to make a plot with log scaling on the y axis. Syntax:
2 min read
Matplotlib.pyplot.figlegend() function in Python
Matplotlib is a Python library used for creating, animations, and editing graphs, plots, and figures using Pyplot. Matplotlib.pyplot has many functions defined in it to use, as per the preference and requirement of the user demands. matplotlib.pyplot.figlegend() function This is used to place a legend on the figure. A legend in Matplotlib is simila
3 min read
matplotlib.pyplot.step() function in Python
The step() function designs the plot such that, it has a horizontal baseline to which the data points will be connected by vertical lines. This kind of plot is used to analyze at which points the change in Y-axis value has occurred exactly with respect to X-axis. This is very useful in discrete analysis. The step plotting can be combined with any o
4 min read
Matplotlib.pyplot.pcolor() function in Python
Matplotlib is the well-known Python package used in data visualization. Numpy is the numerical mathematics extension of Matplotlib. Matplotlib is capable of producing high-quality graphs, charts, and figures. Matplotlib produces object-oriented API for embedding plots into projects using GUI toolkits like Tkinter, wxPython, or Qt. John D. Hunter wa
2 min read
Matplotlib.pyplot.table() function in Python
Matplotlib.pyplot.table() is a subpart of matplotlib library in which a table is generated using the plotted graph for analysis. This method makes analysis easier and more efficient as tables give a precise detail than graphs. The matplotlib.pyplot.table creates tables that often hang beneath stacked bar charts to provide readers insight into the d
3 min read
Matplotlib.pyplot.text() function in Python
This function is used to add a text to the axes at location x, y in data coordinates. Syntax: matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)parameters Descriptionx, y:floatThe position to place the text. By default, this is in data coordinates. The coordinate system can be changed using the transform parameter.s :strThe text.fontdict : di
1 min read
Matplotlib.pyplot.fill() function in Python
Matplotlib.pyplot.fill() function is used to fill the area enclosed by polygon /curve. Syntax: matplotlib.pyplot.fill(*args, data=None, **kwargs) Parameters: *args: sequence of x, y, [color] sequence of x,y = To traverse the boundaries of the polygon or curve defined by lists of x and y positions of its nodes.color = To change the default fill colo
2 min read
Matplotlib.pyplot.colorbar() function in Python
Colorbars are a visualization of the mapping from scalar values to colors. In Matplotlib they are drawn into a dedicated axis. Note: Colorbars are typically created through Figure.colorbar or its pyplot wrapper pyplot.colorbar, which uses make_axes and Colorbar internally. As an end-user, you most likely won't have to call the methods or instantiat
2 min read
Matplotlib.pyplot.loglog() function in Python
Prerequisites: Matplotlib Matplotlib is a comprehensive library for creating interactive, static and animated visualizations in python. Using general-purpose GUI toolkits like wxPython, SciPy, Tkinter or SciPy, it provides an object-oriented API for embedding plots into applications. Matplotlib.pyplot is a collection of functions that makes Matplot
2 min read
Matplotlib.pyplot.subplot() function in Python
Prerequisites: matplotlib subplot() function adds subplot to a current figure at the specified grid position. It is similar to the subplots() function however unlike subplots() it adds one subplot at a time. So to create multiple plots you will need several lines of code with the subplot() function. Another drawback of the subplot function is that
2 min read
Matplotlib.pyplot.barh() function in Python
A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axis of the plot represents the spe
3 min read
Matplotlib.pyplot.margins() function in Python
Prerequisites: Matplotlib Matplotlib.pyplot.margins() is a function used to set the margins of the x and y axes. All input parameters must be a float that too within the range [0, 1]. We cannot pass both positional and keyword arguments at once as that will raise a TypeError. The padding added to each limit of the axes is the margin times the data
2 min read
Matplotlib.pyplot.plot_date() function in Python
Matplotlib is a module package or library in Python which is used for data visualization. Pyplot is an interface to a Matplotlib module that provides a MATLAB-like interface. The matplotlib.pyplot.plot_date() function is like the regular plot() function, but it's tailored for showing data over dates. Think of it as a handy tool for visualizing even
3 min read
Matplotlib.pyplot.broken_barh() in Python
Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. Pyplot is a collection of command style functions that make matplotlib work like MATLAB. matplotlib.pyplot.broken_barh() The function broken_barh() is used to Plot a horizontal sequence of rectan
2 min read
Matplotlib.pyplot.axis() in Python
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python and the advantage of being free and open-source. matplotlib.pyplot.axis() This function is us
1 min read
Matplotlib.pyplot.get_fignums() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. matplotlib.pyplot.get_fignums() method The ge
2 min read
Python | Matplotlib.pyplot ticks
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2003.One of the greatest benefits of visualization is that it allows us visual access to huge
3 min read
Matplotlib.pyplot.waitforbuttonpress() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. matplotlib.pyplot.waitforbuttonpress() method
2 min read
Matplotlib.pyplot.streamplot() in Python
Stream plot is basically a type of 2D plot used majorly by physicists to show fluid flow and 2D field gradients .The basic function to create a stream plot in Matplotlib is: ax.streamplot(x_grid, y_grid, x_vec, y_vec, density=spacing) Here x_grid and y_grid are arrays of the x and y points.The x_vec and y_vec represent the stream velocity of each p
7 min read
Matplotlib.pyplot.ylim() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.ylim() Function The ylim() function in pyplot module of matplotlib library is used to get or set the y-limits of the current axes. Syntax
2 min read
matplotlib.pyplot.arrow() in Python
Matplotlib is a very powerful plotting library useful for those working with Python and NumPy. And for making statistical interference, it becomes very necessary to visualize our data and Matplotlib is the tool that can be very helpful for this purpose. It provides MATLAB like interface only difference is that it uses Python and is open source. mat
2 min read
Matplotlib.pyplot.ylabel() in Python
Matplotlib is a very powerful plotting library useful for those working with Python and NumPy. And for making statistical interference, it becomes very necessary to visualize our data and Matplotlib is the tool that can be very helpful for this purpose. matplotlib.pyplot.ylabel() This function sets the label for the y-axis of the plot. Syntax: matp
2 min read
Matplotlib.pyplot.acorr() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.acorr() Function The acorr() function in pyplot module of matplotlib library is used to plot the autocorrelation of x (array-like). Synta
2 min read
matplotlib.pyplot.angle_spectrum() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.acorr() Function: The angle_spectrum() function in pyplot module of matplotlib library is used to plot the angle spectrum. Generally, it
2 min read
Matplotlib.pyplot.thetagrids() in Python
Matplotlib is a plotting library of Python programming language and its numerical mathematics module is NumPy. matplotlib.pyplot is a collection of command style functions that make matplotlib work like the MATLAB Tool. Each of the pyplot functions makes certain changes to a figure: e.g., creating a figure, creating a plot area in a figure, plots s
2 min read