How to plot a graph in Python?

Graphs in Python can be plotted by using the Matplotlib library. Matplotlib library is mainly used for graph plotting and provides inbuilt functions to draw line graphs, bar graphs, histograms, and pie charts.

You need to install matplotlib before using it to plot graphs ?

pip install matplotlib

Plot a Line Graph

We will plot a simple line graph using matplotlib. The following steps are involved in plotting a line ?

  • Import matplotlib.pyplot

  • Specify the x-coordinates and y-coordinates of the line

  • Plot the specified points using .plot() function

  • Name the x-axis and y-axis using .xlabel() and .ylabel() functions

  • Give a title to the graph using .title() function

  • Show the graph using .show() function

Example

import matplotlib.pyplot as plt

x = [1, 3, 5, 7]
y = [2, 4, 6, 1]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("A simple line graph")
plt.show()

The above code plots the points (1,2), (3,4), (5,6), (7,1) and joins these points with a line.

1 3 5 7 1 2 4 6 X-axis Y-axis A simple line graph

Plot a Bar Graph

A bar graph represents data using rectangles of different heights at specific positions on the x-axis. The following steps are involved in drawing a bar graph ?

  • Import matplotlib.pyplot

  • Specify the x-coordinates where the left bottom corner of the rectangle lies

  • Specify the heights of the bars or rectangles

  • Specify the labels for the bars

  • Plot the bar graph using .bar() function

  • Give labels to the x-axis and y-axis

  • Give a title to the graph

  • Show the graph using .show() function

Example

import matplotlib.pyplot as plt

left_coordinates = [1, 2, 3, 4, 5]
heights = [10, 20, 30, 15, 40]
bar_labels = ['One', 'Two', 'Three', 'Four', 'Five']
plt.bar(left_coordinates, heights, tick_label=bar_labels, width=0.6, color=['red', 'green', 'blue', 'orange', 'purple'])
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("A simple bar graph")
plt.show()

The width parameter specifies the width of each bar, and the color parameter specifies the colors of the bars.

One Two Three Four Five 0 10 20 30 40 X-axis Y-axis A simple bar graph

Conclusion

Matplotlib provides simple functions to create various types of graphs in Python. Use plot() for line graphs and bar() for bar graphs. Always remember to add labels and titles for better visualization.

Updated on: 2026-03-25T22:50:41+05:30

64K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements