×

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 AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

Python String capitalize() method

Python String capitalize() method The string.capitalize() method in Python returns a copy of the string with only its first character capitalized. Syntax string.capitalize() Parameter NA Return This function returns a string where the first character is upper...

1 minute read.

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.

Scraping data in python

Data scraping is a technique in which one program extracts a set of data from the output of another program. Web scraping is the most common application of this technique....

6 minutes read.

Handling missing keys in Python dictionaries

In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value...

3 minutes read.

XXhash Python Examples

XXhash Python: xxHash is an extremely rapid hash calculation that operates inside the confines of RAM. Code is incredibly convenient, and hashes (almost nothing/large endian) are same at all levels. Execution of...

4 minutes read.

What is Python 2

Python is a widely used high-level language. The initial work on developing python was begun in the late 1980s. In 1989, Guido Van Rossum started to work on it. Initially,...

3 minutes read.

Python Tuple Methods

Python Tuple Methods Python has two built-in methods that are used for tuples. The following are the two methods: Method Description count() The tuple.count() method in Python returns the number of times a...

1 minute read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

Python program to find the greatest among two numbers

Python program to find the greatest among two numbers We have many approaches to get the largest number among the two numbers, and here we will discuss a few of them....

2 minutes read.

OSError in Python

Python: 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 is said...

4 minutes read.

Python Escape Characters

In this tutorial, we will learn how to use the Escape Characters in Python. Escape Character: Escape Characters are used for some special meaning in our statements. It is denoted or represented...

3 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Python random.seed() function

The random module in Python produces a random number or pseudo-random data, that is, deterministic. The seed function records the state of a random function to provide the same random...

6 minutes read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

Python vs Java

There are a lot of programming languages out there, and every day, a new programming language is developing in some parts of the world. Each programming language is a mixture...

5 minutes read.

Python Packages

A package is a collection of Python modules that share a similar namespace and are generated by putting all of the modules in a single directory with certain special files...

6 minutes read.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

4 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.