×

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 Set intersection_update() method

Python Set intersection_update() method The set.intersection_update() method in Python removes the items that is not present in both sets. It is different from the set.intersection() method, because the intersection()method returns a new set, with only  the common elements...

2 minutes read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Python Program to Find the Greatest Among Three Numbers

Python Program to find the greatest among three numbers We have many approaches to get the largest of three numbers, and here we will discuss a few of them. This python...

2 minutes read.

How to Convert String to List In Python?

How to Convert String to List In Python? We all are familiar with what strings and lists are, let us have a quick revision on them- Strings are a sequence of characters...

4 minutes read.

Python String title() method

Python String title() method The string.title() method in Python returns a string where the first character in every word is upper case. If the word contains a number or a symbol,...

1 minute read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

ER diagram of the Bank Management System in python

What is an ER diagram? The full form of the ER diagram is the Entity Relationship diagram. This diagram is used in database management systems to have a rough idea of...

3 minutes read.

How to write a program in python?

How to write a program in python? In python, writing programs is not a big deal. What we need to work on is our logic and some basic rules of this...

4 minutes read.

Python Os sep

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....

3 minutes read.

Python Project Ideas

One of the most widely used programming languages today is Python. This pattern appears set to continue through 2023 and beyond. Therefore, working on some current Python project ideas is the...

10 minutes read.

Android apps for coding in python

Nowadays, it is the generation of smartphones. The world can be seen and acknowledged with a single click on your mobile phone. Everyone uses mobile phones to do any work,...

9 minutes read.

How to Download all Modules in Python

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....

3 minutes read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

Python Pascal Triangle

Python Pascal Triangle Pascal triangle A pascal triangle is a number pattern of triangular array of the binomial coefficients. For designing a pascal triangle, we write a function in the program which...

5 minutes read.

Is Python Case Sensitive

Case sensitivity is the mode of dealing with the written alphabet. The cases of the alphabet are examined and based on these words are being treated. The uppercase and lowercase...

3 minutes read.

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Python String join() method

Python String join() method The String.join() method in Python concatenates each element of an iterable (such as list, string and tuple) to the given string and returns the concatenated string. Syntax string.join(seq) Parameter Seq: This...

1 minute read.