The Wayback Machine - https://web.archive.org/web/20241128055352/https://www.geeksforgeeks.org/graph-plotting-in-python-set-1/
Open In App

Graph Plotting in Python | Set 1

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This series will introduce you to graphing in Python with Matplotlib, which is arguably the most popular graphing and data visualization library for Python.
Installation
The easiest way to install matplotlib is to use pip. Type the following command in the terminal: 

pip install matplotlib

OR, you can download it from here and install it manually. 

How to plot a graph in Python?

There are various ways to do this in Python. here we are discussing some generally used methods for plotting matplotlib in Python. those are the following.

  • Plotting a Line
  • Plotting Two or More Lines on the Same Plot 
  • Customization of Plots 
  • Plotting Matplotlib Bar Chart
  • Plotting Matplotlib Histogram
  • Plotting Matplotlib Scatter plot
  • Plotting Matplotlib Pie-chart
  • Plotting Curves of Given Equation

Plotting a line

In this example, the code uses Matplotlib to create a simple line plot. It defines x and y values for data points, plots them using `plt.plot()`, and labels the x and y axes with `plt.xlabel()` and `plt.ylabel()`. The plot is titled “My first graph!” using `plt.title()`. Finally, the `plt.show()` function is used to display the graph with the specified data, axis labels, and title.

Python
# importing the required module
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: 

mp1


Plotting Two or More Lines on Same Plot 

In this example code uses Matplotlib to create a graph with two lines. It defines two sets of x and y values for each line and plots them using `plt.plot()`. The lines are labeled as “line 1” and “line 2” with `label` parameter. Axes are labeled with `plt.xlabel()` and `plt.ylabel()`, and the graph is titled “Two lines on the same graph!” with `plt.title()`. The legend is displayed using `plt.legend()`, and the `plt.show()` function is used to visualize the graph with both lines and labels.

Python
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: 

mp2

Customization of Plots 

In this example code uses Matplotlib to create a customized line plot. It defines x and y values, and the plot is styled with a green dashed line, a blue circular marker for each point, and a marker size of 12. The y-axis limits are set to 1 and 8, and the x-axis limits are set to 1 and 8 using `plt.ylim()` and `plt.xlim()`. Axes are labeled with `plt.xlabel()` and `plt.ylabel()`, and the graph is titled “Some cool customizations!” with `plt.title()`.

Python
import matplotlib.pyplot as plt

# x axis values
x = [1,2,3,4,5,6]
# corresponding y axis values
y = [2,4,1,5,2,6]

# plotting the points 
plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3,
         marker='o', markerfacecolor='blue', markersize=12)

# setting x and y axis range
plt.ylim(1,8)
plt.xlim(1,8)

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

# giving a title to my graph
plt.title('Some cool customizations!')

# function to show the plot
plt.show()

Output: 

mp3

Plotting Matplotlib Using Bar Chart

In this example code uses Matplotlib to create a bar chart. It defines x-coordinates (`left`), heights of bars (`height`), and labels for the bars (`tick_label`). The `plt.bar()` function is then used to plot the bar chart with specified parameters such as bar width, colors, and labels. Axes are labeled with `plt.xlabel()` and `plt.ylabel()`, and the chart is titled “My bar chart!” using `plt.title()`.

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 :

mp4


Plotting Matplotlib Using Histogram

In this example code uses Matplotlib to create a histogram. It defines a list of age frequencies (ages), sets the range of values from 0 to 100, and specifies the number of bins as 10. The plt.hist() function is then used to plot the histogram with the provided data and formatting, including the color, histogram type, and bar width. Axes are labeled with plt.xlabel() and plt.ylabel(), and the chart is titled “My histogram” using plt.title().

Python
import matplotlib.pyplot as plt

# frequencies
ages = [2,5,70,40,30,45,50,45,43,40,44,
        60,7,13,57,18,90,77,32,21,20,40]

# setting the ranges and no. of intervals
range = (0, 100)
bins = 10  

# plotting a histogram
plt.hist(ages, bins, range, color = 'green',
        histtype = 'bar', rwidth = 0.8)

# x-axis label
plt.xlabel('age')
# frequency label
plt.ylabel('No. of people')
# plot title
plt.title('My histogram')

# function to show the plot
plt.show()

Output:

mp5


Plotting Matplotlib Using Scatter Plot 

In this example code uses Matplotlib to create a scatter plot. It defines x and y values and plots them as scatter points with green asterisk markers (`*`) of size 30. Axes are labeled with `plt.xlabel()` and `plt.ylabel()`, and the plot is titled “My scatter plot!” using `plt.title()`. The legend is displayed with the label “stars” using `plt.legend()`, and the resulting scatter plot is shown using `plt.show()`.

Python
import matplotlib.pyplot as plt

# x-axis values
x = [1,2,3,4,5,6,7,8,9,10]
# y-axis values
y = [2,4,5,7,6,8,9,11,12,12]

# plotting points as a scatter plot
plt.scatter(x, y, label= "stars", color= "green", 
            marker= "*", s=30)

# x-axis label
plt.xlabel('x - axis')
# frequency label
plt.ylabel('y - axis')
# plot title
plt.title('My scatter plot!')
# showing legend
plt.legend()

# function to show the plot
plt.show()

Output:
 

mp6


Plotting Matplotlib Using Pie-chart 

In this example code uses Matplotlib to create a pie chart. It defines labels for different activities (`activities`), the portion covered by each label (`slices`), and colors for each label (`colors`). The `plt.pie()` function is then used to plot the pie chart with various formatting options, including start angle, shadow, explosion for a specific slice, radius, and autopct for percentage display. The legend is added with `plt.legend()`, and the resulting pie chart is displayed using `plt.show()`.

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()

The output of above program looks like this:
 

mp7


Plotting Curves of Given Equation 

In this example code uses Matplotlib and NumPy to create a sine wave plot. It generates x-coordinates from 0 to 2π in increments of 0.1 using `np.arange()` and calculates the corresponding y-coordinates by taking the sine of each x-value using `np.sin()`. The points are then plotted using `plt.plot()`, resulting in a sine wave. Finally, the `plt.show()` function is used to display the sine wave plot.

Python
# importing the required modules
import matplotlib.pyplot as plt
import numpy as np

# setting the x - coordinates
x = np.arange(0, 2*(np.pi), 0.1)
# setting the corresponding y - coordinates
y = np.sin(x)

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

# function to show the plot
plt.show()

Output:
 

mp8

So, in this part, we discussed various types of plots we can create in matplotlib. There are more plots that haven’t been covered but the most significant ones are discussed here – 


 If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Graph Plotting in Python | Set 1 – FAQs

What libraries are available for plotting graphs in Python?

Python provides several powerful libraries for plotting graphs:

  • Matplotlib: The most widely used library for creating various types of static, animated, and interactive plots. It’s highly customizable and versatile.
  • Seaborn: Built on top of Matplotlib, Seaborn simplifies the creation of attractive and informative statistical graphics, with default themes and color palettes.
  • Plotly: Known for interactive and web-based plots, Plotly supports a range of chart types and is useful for creating dashboards and complex visualizations.
  • Bokeh: Designed for interactive plots and web applications, Bokeh allows for the creation of rich, interactive visualizations.
  • Altair: A declarative statistical visualization library that provides concise syntax for generating complex plots.

How to plot a simple line graph in Python?

To plot a simple line graph, use the following code snippet. This example uses Matplotlib to create a line graph of x versus y:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]

plt.plot(x, y)
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Line Graph')
plt.show()

What are the basic options for customizing graphs in Python?

Customizing graphs can involve changing line styles, colors, markers, and adding grid lines:

plt.plot(x, y, linestyle='--', color='red', marker='o')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Customized Line Graph')
plt.grid(True)
plt.show()

How to save plots as images in Python?

To save a plot as an image file, use the savefig() method. This method allows you to specify the file format:

plt.plot(x, y)
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Line Graph')
plt.savefig('plot.png') # Save as PNG file
plt.show()


Previous Article
Next Article

Similar Reads

Graph Plotting in Python | Set 2
Graph Plotting in Python | Set 1 Subplots Subplots are required when we want to show two or more plots in same figure. We can do it in two ways using two slightly different methods.Method 1 Python Code # importing required modules import matplotlib.pyplot as plt import numpy as np # function to generate coordinates def create_plot(ptype): # setting
9 min read
Graph Plotting in Python | Set 3
Graph Plotting in Python | Set 1 Graph Plotting in Python | Set 2 Matplotlib is a pretty extensive library which supports Animations of graphs as well. The animation tools center around the matplotlib.animation base class, which provides a framework around which the animation functionality is built. The main interfaces are TimedAnimation and FuncAn
6 min read
Python | Matplotlib Graph plotting using object oriented API
In object-oriented API, first, we create a canvas on which we have to plot the graph and then we plot the graph. Many people prefer object-oriented API because it is easy to use as compared to functional API. Let's try to understand this with some examples. Example #1: # importing matplotlib library import matplotlib.pyplot as plt # x axis values x
2 min read
Plotting a trend graph in Python
Prerequisites: Matplotlib A trend Graph is a graph that is used to show the trends data over a period of time. It describes a functional representation of two variables (x , y). In which the x is the time-dependent variable whereas y is the collected data. The graph can be in shown any form that can be via line chart, Histograms, scatter plot, bar
3 min read
Plotting Sine and Cosine Graph using Matplotlib in Python
Data visualization and Plotting is an essential skill that allows us to spot trends in data and outliers. With the help of plots, we can easily discover and present useful information about the data. In this article, we are going to plot a sine and cosine graph using Matplotlib in Python. Matplotlib is a Python library for data visualization and pl
3 min read
Plotting graph For IRIS Dataset Using Seaborn And Matplotlib
Matplotlib.pyplot library is most commonly used in Python in the field of machine learning. It helps in plotting the graph of large dataset. Not only this also helps in classifying different dataset. It can plot graph both in 2d and 3d format. It has a feature of legend, label, grid, graph shape, grid and many more that make it easier to understand
2 min read
Plotting Bar Graph in Matplotlib from a Pandas Series
Bar graphs are one of the most common types of data visualizations used to represent categorical data with rectangular bars. Each bar's height or length corresponds to the value it represents. In Python, the combination of Pandas and Matplotlib libraries provides a powerful toolset for creating bar graphs. This article will guide you through the pr
3 min read
Python | Plotting charts in excel sheet using openpyxl module | Set - 1
Prerequisite: Reading & Writing to excel sheet using openpyxl Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let's see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data poi
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set – 2
Prerequisite: Python | Plotting charts in excel sheet using openpyxl module | Set – 1 Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set 3
Prerequisite : Plotting charts in excel sheet using openpyxl module Set - 1 | Set – 2Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of r
7 min read
Python | Plotting charts in excel sheet with Data Tools using XlsxWriter module | Set - 1
Prerequisite: Create and Write on an excel sheetXlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot charts with different types of Data Tools using realtime data. Charts are composed of at least one series of one or mor
7 min read
Python | Plotting charts in excel sheet with data tools using XlsxWriter module | Set – 2
Prerequisite: Create and Write on an excel sheetXlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot charts with different types of Data Tools using realtime data.Charts are composed of at least one series of one or more
7 min read
Python | Geographical plotting using plotly
Geographical plotting is used for world map as well as states under a country. Mainly used by data analysts to check the agriculture exports or to visualize such data. plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many
2 min read
bokeh.plotting.figure.diamond_cross() function in Python
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like a notebook, HTML and server. Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. bokeh.plotting.fig
2 min read
3D Wireframe plotting in Python using Matplotlib
To create static, animated and interactive visualizations of data, we use the Matplotlib module in Python. The below programs will depict 3D wireframe. visualization of data in Python. In-order to visualize data using 3D wireframe we require some modules from matplotlib, mpl_toolkits and numpy library. Example 1: C/C++ Code # importing modules from
1 min read
Python | Plotting Area charts in excel sheet using XlsxWriter module
Prerequisite: Create and write on an excel file XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data points. Series the
6 min read
Python | Plotting bar charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel file.XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Bar charts using realtime data. Charts are composed of at least one series of one or more data points
6 min read
Python | Plotting Radar charts in excel sheet using XlsxWriter module
Prerequisite:Create and Write on excel file XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Radar charts using realtime data. Charts are composed of at least one series of one or more data points.
6 min read
Python | Plotting scatter charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel file. XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Scatter charts using realtime data. Charts are composed of at least one series of one or more data p
10 min read
Python | Plotting column charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel file.XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Column charts using realtime data. Charts are composed of at least one series of one or more data poi
7 min read
Python | Plotting Pie charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel sheet XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different types of pie charts using realtime data. Charts are composed of at least one series of one or more data poin
5 min read
Python | Plotting Doughnut charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel sheet XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different variety of doughnut charts using realtime data. Charts are composed of at least one series of one or more da
7 min read
Python | Plotting Stock charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel sheet XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot Stock charts using realtime data. Charts are composed of at least one series of one or more data points. Series themse
3 min read
Python | Plotting Line charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel sheet XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot Line charts using realtime data. Charts are composed of at least one series of one or more data points. Series themsel
3 min read
Python | Plotting Combined charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel sheetXlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations, and plotting graphs. Let’s see how to plot Combined charts using real-time data. Charts are composed of at least one series of one or more data points. Series th
5 min read
Python | Plotting an Excel chart with pattern fills in column using XlsxWriter module
Prerequisite: Create and Write on an excel sheetXlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot chart with pattern fills, using realtime data.Charts are composed of at least one series of one or more data points. Se
3 min read
Python | Plotting Different types of style charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel sheet XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different types of Style charts, using realtime data. Charts are composed of at least one series of one or more data p
3 min read
Python | Plotting an Excel chart with Gradient fills using XlsxWriter module
Prerequisite: Create and Write on an excel sheetXlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations, and plotting graphs. Let’s see how to plot a chart with Gradient fills, using real-time data.Charts are composed of at least one series of one or more data point
5 min read
Python | Plotting column charts in excel sheet with data tables using XlsxWriter module
Prerequisite: Create and Write on an excel sheetXlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot charts with Data tables using realtime data.Charts are composed of at least one series of one or more data points. Seri
5 min read
Python | Matplotlib Sub plotting using object oriented API
Plotting using Object Oriented(OO) API in matplotlib is an easy approach to plot graphs and other data visualization methods. The simple syntax to create the class and object for sub-plotting is - class_name, object_name = matplotlib.pyplot.subplots('no_of_rows', 'no_of_columns') Let's take some examples to make it more clear. Example #1: # importi
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg