Matplotlib.pyplot.plot() function in Python
Last Updated :
29 Nov, 2023
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
plt.plot([1, 2, 3])
plt.title('Matplotlib Line Plot Example')
plt.draw()
plt.show()
|
Output:

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
x = np.linspace(0, 2*np.pi, 100)
y1, y2 = np.sin(x), np.cos(x)
plt.plot(x, y1, label='Sin(x)', color='b')
plt.plot(x, y2, label='Cos(x)', color='r', linestyle='--')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Multiple Lines Plot')
plt.legend()
plt.show()
|
Output

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
np.random.seed(42)
x = np.random.rand(50)
y = np.random.rand(50)
plt.plot(x, y, marker='o', linestyle='', markersize=8, color='r', label='Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Example')
plt.legend()
plt.show()
|
Output:

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
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
xdata = np.random.random([2, 10])
xdata1 = xdata[0, :]
xdata2 = xdata[1, :]
xdata1.sort()
xdata2.sort()
ydata1 = xdata1 ** 2
ydata2 = 1 - xdata2 ** 3
plt.plot(xdata1, ydata1, color ='tab:blue')
plt.plot(xdata2, ydata2, color ='tab:orange')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.title('matplotlib.pyplot.plot() example 2')
plt.show()
|
Output

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
strings.SplitN() Function in Golang with Examples
strings.SplitN() Function() is a string manipulation function in Go language. It is used to split a given string into substrings separated by a separator. This function returns the slices of all substrings between those separators. Syntax: func SplitN(s, sep string, n int) []string Here, s is the st
3 min read
Split a string on multiple delimiters in Python
In this article, we will explore various methods to split a string on multiple delimiters in Python. The simplest approach is by using re.split(). Using re.split()The re.split() function from the re module is the most straightforward way to split a string on multiple delimiters. It uses a regular ex
2 min read
JSTL fn:split() Function
The JSTL fn:split() function is used to split the input string into an array of different substrings based on the delimiter. This function is helpful to the parsing of strings within the JavaServer Pages, which also allows the developers to extract the substring from the main string. In this article
2 min read
How to convert String to structtype in Scala?
In Scala, whenever one deals with structured data such as JSON or CSV, there is usually a need to convert strings into structured data types like "StructType". This is very important for efficient processing and analysis of data, particularly in big data setups where Apache Spark is mostly used. To
3 min read
Split and Parse a string in Python
In Python, working with strings is a fundamental aspect of programming. Strings are sequences of characters and often contain structured data that needs to be processed or analyzed. The common operations performed on strings are splitting and parsing. Splitting a String in PythonIn Python, you can s
5 min read
String concatenation in Scala
A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. when a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method
2 min read
String Manipulation in R
String manipulation basically refers to the process of handling and analyzing strings. It involves various operations concerned with modification and parsing of strings to use and change its data. R offers a series of in-built functions to manipulate the contents of a string. In this article, we wil
5 min read
How to Create a JSON Object in Scala?
JSON(JavaScript Object Notation) plays an important role in web development and data transmission. In web applications, we frequently use JSON, a lightweight data transmission standard. Working with JSON data is made easy using Scala, a sophisticated programming language for the Java Virtual Machine
2 min read
Convert List of Characters to String in Java
Given a list of characters. In this article, we will write a Java program to convert the given list to a string. Example of List-to-String ConversionInput : list = {'g', 'e', 'e', 'k', 's'} Output : "geeks" Input : list = {'a', 'b', 'c'} Output : "abc" Strings - Strings in Java are objects that are
4 min read
How to split Array in Scala?
Arrays are a fundamental data structure in Scala, used to store collections of elements of the same type. Splitting an array involves dividing it into smaller sub-arrays based on specific criteria. This article explores different methods for achieving this in Scala. Table of Content 1. Using `splitA
3 min read
How to Convert Scala Map into JSON String?
In this article, we will learn to convert a Scala Map into JSON String. We can convert Scala Map to JSON String using various libraries and custom conversion functions. Table of Content What is Scala Map?What is JSON String?Converting Scala Map into JSON StringWhat is Scala Map?In Scala, a Map is a
4 min read
How does Collect function Work in Scala?
The collect function in Scala is utilized to extract elements from a collection that satisfy a specified condition defined by a partial function. It can be invoked on any collection type, whether mutable or immutable and always returns a new collection containing the elements that meet the condition
3 min read
How to format numbers as percentages in Scala?
In this article, we will learn to format numbers as percentages in Scala using various methods such as f, %, and java.text.DecimalFormat. Formatting numbers as percentages that consist of representing numerical values as ratios out of 100, typically with a specific number of decimal places. Example
2 min read
Convert a String to a List of Characters in Java
In Java, to convert a string into a list of characters, we can use several methods depending on the requirements. In this article, we will learn how to convert a string to a list of characters in Java. Example: In this example, we will use the toCharArray() method to convert a String into a characte
3 min read
Python - Swap commas and dots in a String
In this article, we'll explore how to swap commas and dots in a string in Python. Using str.translate() str.translate() that allows for character substitution within a string using a translation table. It enables quick transformations, such as swapping characters like commas and dots. Example: [GFGT
2 min read
How to Escape Special Symbols in Scala String at Runtime?
Handling special symbols' interior strings is an average project in Scala, especially whilst interacting with dynamically created cloth or consumer enter. If special symbols like quote marks, backslashes, or newline characters are not effectively escaped, they could bring about syntax errors or unex
3 min read
Scala | String Interpolation
String Interpolation refers to substitution of defined variables or expressions in a given String with respected values. String Interpolation provides an easy way to process String literals. To apply this feature of Scala, we must follow few rules: String must be defined with starting character as s
3 min read
strings.Fields() Function in Golang With Examples
strings.Fields() Function in Golang is used to splits the given string around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of str or an empty slice if str contains only white space. Syntax: func Fields(str string) []s
2 min read
How to remove First and Last character from String in Scala?
In this article, we will explore different approaches to removing the first and last character from a string in Scala. Table of Content Using substring methodUsing drop and dropRight methodsUsing substring methodIn this approach, we are using the substring method which takes two arguments the starti
1 min read