Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.pyplotSpecify the x-coordinates and y-coordinates of the line
Plot the specified points using
.plot()functionName the x-axis and y-axis using
.xlabel()and.ylabel()functionsGive a title to the graph using
.title()functionShow 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.
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.pyplotSpecify 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()functionGive 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.
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.
