×

How to Plot Graphs Using Python?

In this article, we are going to learn about how to plot different types of graphs using Python. We are going to use different approaches for every type of graph. We will also build the Python programs to plot the graphs.

Plotting a straight line

Approach for the Program

The following steps are followed in order to build a program to plot a straight line.

  • Lists should be used to define the x-axis and associated y-axis values.
  • Utilize the.plot() function to plot them on a canvas.
  • Utilizing the .xlabel() and .ylabel() procedures, declare the x-axis and y-axis names.
  • Utilize the.title() function to give your plot a title.
  • Finally, we utilise the.show() function to display your plot.

Example:

#Program to Plot a Straight line in Python
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3]
# Corresponding y axis values
y = [2,4,1]


# Plotting the points
plt.plot(x, y)


# Naming the x axis
plt.xlabel('x - axis')
# Naming the y axis
plt.ylabel('y - axis')


# Giving a title to my graph
plt.title('My first graph!')


# Function to show the plot
plt.show()

Output:

How to Plot Graphs Using Python

Plotting More than One line in Python

Approach for the Program

  • On the same graph, two lines are plotted here. By assigning each one a name (label), which is supplied as an argument to the.plot() function, we can distinguish between them.
  • A legend is a short, rectangular box that contains information regarding the characteristics of lines and its color. Using the .legend() function, we can add the legend to our plot.

Example:

#Program to Plot more than One Line in Single Graph
import matplotlib.pyplot as plt
# Line 1 points
x1 = [1,2,3]
y1 = [2,4,1]
# Plotting the line 1 points
plt.plot(x1, y1, label = "line 1")


# Line 2 points
x2 = [1,2,3]
y2 = [4,1,3]
# Plotting the line 2 points
plt.plot(x2, y2, label = "line 2")


# Naming the x axis
plt.xlabel('x - axis')
# Naming the y axis
plt.ylabel('y - axis')
# Giving a title to my graph
plt.title('Two lines on same graph!')


# Show a legend on the plot
plt.legend()


# Function to show the plot
plt.show()

Output:

How to Plot Graphs Using Python

Plotting a Bar Graph using Python

Approach for the Program

  • Here, a bar chart is plotted using the plt.bar() function.
  • Along with the heights of the bars, the x-coordinates of the left side of the bars are passed.
  • By defining tick_labels, you may also give the x-axis coordinates some names.

Example:

#Program to plot Bar Graph in Python
import matplotlib.pyplot as plt


# x-coordinates of left sides of bars
left = [1, 2, 3, 4, 5]


# Heights of bars
height = [10, 24, 36, 40, 5]


# Labels for bars
tick_label = ['one', 'two', 'three', 'four', 'five']


# Plotting a bar chart
plt.bar(left, height, tick_label = tick_label,
		width = 0.8, color = ['red', 'green'])


# Naming the x-axis
plt.xlabel('x - axis')
# Naming the y-axis
plt.ylabel('y - axis')
# Plot title
plt.title('My bar chart!')


# Function to show the plot
plt.show()

Output:

How to Plot Graphs Using Python

Program to Plot a Pie Chart in Python

Approach for the Program

  • Here, we use the plt.pie() method to plot a pie chart.
  • The labels are first defined using a list named activities.
  • Then, a list named slices can be used to define a piece of each label.
  • Each label's color is specified using a list called colors.
  • Each label in the pie chart will have a shadow if shadow = True is set.
  • startangle spins the beginning of the pie chart in a counterclockwise direction with respect to the x-axis.
  • The percentage of radius by which we offset each wedge is set using explode.
  • Each label's value is formatted using autopct. Here, it is configured to only display percentage values up to one decimal place.

Example:

#Program to plot a Pie Chart in Python
import matplotlib.pyplot as plt
# Defining labels
activities = ['eat', 'sleep', 'work', 'play']


# Portion covered by each label
slices = [3, 7, 8, 6]


# Color for each label
colors = ['r', 'y', 'g', 'b']


# Plotting the pie chart
plt.pie(slices, labels = activities, colors=colors,
		startangle=90, shadow = True, explode = (0, 0, 0.1, 0),
		radius = 1.2, autopct = '%1.1f%%')


# Plotting legend
plt.legend()


# Showing the plot
plt.show()

Output:

How to Plot Graphs Using Python

Related Topics

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Python Subprocess Call Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

StandardScaler in Sklearn

When and How Should You Use StandardScaler? StandardScaler comes into play whenever the properties of the provided dataset change significantly within their ranges or are recorded in different measurement units. Since using...

4 minutes read.

Python globals() function

Python globals() function The globals() function in Python returns the value of the named attribute of object where the ‘name’ must be a string. Syntax globals() Parameter NA Return This function returns the global symbol table as a dictionary. Example...

1 minute read.

Python Word Tokenizer

Python Overview Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. Python is an interpreted language...

4 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Python Selectors

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

Python Variable Scope with Local & Non-local Examples

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

How to build a Virtual Assistant Using Python

What is a virtual assistant? A virtual assistant is a new and very interesting concept in today’s world. When we hear the word “Virtual Assistant”, we can easily visualize “Jarvis or...

8 minutes read.

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.

Parameter Passing in Python

In Python, when we characterize capabilities with default values for specific boundaries, it is said to have its contentions set as a possibility for the client. Clients can either pass their...

3 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Python List pop() method

Python List pop() method The list.pop() method removes the item at the specified position in the list, and return it. If no index is specified, this method removes and returns the last item in the list. Syntax list.pop([i]) Parameter i:...

1 minute read.

Algorithm for Factorial of a number in Python

What is a Factorial Number? In mathematics, the factorial of a positive integer n, denoted by n!. It is the product of all positive integers less than or equal to n. For...

3 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

Defaultdict in Python

In this tutorial, we will study What is defaultdict in Python We will understand it with the aid of certain examples. Before this, we will have a look at dictionaries...

3 minutes read.