Introduction
Matplotlib is a graphing and plotting library that can be useful for creating
different types of graphs and plots. Such as line charts, pie charts, scatter
plots and 3D plots. Matplotlib can also be used for creating animated and
interactive visualizations. It can also generate output in a variety of
formats which includes PNG, SVG and PDF etc.
Installing Matplotlib
Matplotlib is not built into python. First, we need to install Matplotlib
using the PIP package manager.
pip install matplotlib
If you are using Conda you can use the below command.
conda install matplotlib
You can refer to more about installation options on the Matplotlib
installation page.
Plotting Simple Graph using Matplotlib
First, we need to import pyplot from Matplotlib library. After
that line, we give 2 python lists as arguments to plot() function
specifying Y values and X values for the graph. then we set the label for both
the x and y axis and the title. Finally, we call the show() function
that displays our plot in a window.
#importing pyplot from matplotlib library
import matplotlib.pyplot as pyplot
# plot the graph using given values
pyplot.plot(
[1, 2, 3, 4], # Y values
[0.5, 1.0, 1.5, 2.0] # X values
)
# setting x and y axis labels
pyplot.xlabel('x-axis-label')
pyplot.ylabel('y-axis-label')
# setting the title
pyplot.title('This is the title')
# display the chart in a window
pyplot.show()
Plotting Multiple Graphs Same Plane.
When plotting multiple graphs we need to add different styles, and colours,
and more importantly, we need to add a legend to identify each graph clearly.
In the below code sample, we add a legend using legend() method and
pass arguments for legend background colour, location and title. we also add a
descriptive label for each graph, change the colour and set the style of the
one graph to a dashed line.
import matplotlib.pyplot as pyplot
# plot the graph 1
pyplot.plot(
[0, 1, 2, 3], # Y values
[1, 3, 5, 7], # X values
label = 'y = 2x + 1', # set the label
color = 'blue' # set the color
)
# plot the graph 2
pyplot.plot(
[0, 1, 2, 3], # Y values
[3, 6, 9, 12], # X values
ls = '--', # set the line style
label = 'y = 3x + 3', # set the label
color = '#995789' # set color color
)
# setting x and y axis labels
pyplot.xlabel('x-axis-label')
pyplot.ylabel('y-axis-label')
# setting the title
pyplot.title('This is the title')
# setting the legend
pyplot.legend(
facecolor = 'gray', # legend background
title = 'legend', # legend title
loc = 'upper left' # legend location
)
# setting the grid line
pyplot.grid(True)
# display the chart in a window
pyplot.show()
![]() |
multiple graphs in the same plane |
Plotting Bar Chart
We use the matplotlib pyplot bar() function to draw bar graphs. In
the below examples, we pass the x-coordinates, heights of each bar, bar
width, and colours of each bar.
import matplotlib.pyplot as plt
languages= ['Rust', 'Python', 'Kotlin', 'Javascript', 'C#']
#setting values for bar labels
Salary = [76000, 60000, 55000, 56000, 61000]
# bar colors
bar_colors = ['blue', 'orange', 'cyan', 'brown', 'purple']
# setting the bar chart
plt.bar(
languages, # x coordinates
Salary, # heights of the bars
width = 0.7, # width of the bars
color = bar_colors # bar colors
)
plt.xlabel('Language')
plt.ylabel('Salary')
plt.title('Median Developer Salary By Language')
plt.show()
![]() |
Bar chart matplotlib |
Horizontal Bar Charts
You can create the above graph horizontal by using
barh() matplotlib pyplot function instead of bar() function. The
below code demonstrates it.
import matplotlib.pyplot as plt
languages= ['Rust', 'Python', 'Kotlin', 'Javascript', 'C#']
#setting values for bar labels
Salary = [76000, 60000, 55000, 56000, 61000]
# bar colors
bar_colors = ['blue', 'orange', 'cyan', 'brown', 'purple']
# setting the bar chart
plt.barh(
languages, # y coordinates
Salary, # width of the bars
height = 0.7, # height of the bars
color = bar_colors # bar colors
)
plt.xlabel('Salary')
plt.ylabel('Language')
plt.title('Median Developer Salary By Language')
plt.show()
![]() |
Horizontal bar graph matplotlib |
Line Graphs using Matplotlib
In the below line graph example, we pass the argument 'bo-' to the
function. in this argument 'bo-' first character 'b' indicates
the
colour of the line and second character 'o' indicates the marker
of each point being plotted and the third character
'-' indicates the
line style
of the graph. In our case, it sets to a blue solid line with circle markers.
import matplotlib.pyplot as plt
month = ['January', 'February', 'March', 'April', 'May', 'June']
profit = [10000, 28000, 13400, 14000, 24400, 21000]
# setting titles and axes headings.
plt.title('Profit in year 2022')
plt.xlabel('Month')
plt.ylabel('Profit')
plt.plot(
month, # setting x values
profit, # setting y values
'bo-' # style of the graph(color, marker, line style)
)
plt.show()
![]() |
Line Graph Matplotlib |
Scatter plot
we use Matplotlib scatter() function to draw a scatter plot. below code
sample demonstrates a scatter plot.
import matplotlib.pyplot as plt
iq = [
[43, 45, 57, 20, 30, 75, 29, 60, 27, 80], # Age
[22, 46, 43, 23, 45, 76, 44, 56, 41, 62] # IQ score
]
maths = [
[29, 70, 20, 57, 30, 44, 60, 25, 32, 62], # Age
[40, 23, 90, 55, 80, 39, 74, 65, 87, 48] # Maths score
]
# plot iq data
plt.scatter(
x = iq[0],
y = iq[1],
color='darkorange',
marker='o',
label='IQ'
)
# plot maths data
plt.scatter(
x = maths[0],
y = maths[1],
color='green',
marker='^',
label='Mathematics'
)
plt.xlabel('Age')
plt.ylabel('Score')
plt.title('Marks Two Subjects')
plt.legend()
plt.show()
![]() |
Scatter Plot |
Pie chart
Matplotlib pyplot pie() function was used to draw below the pie
chart.
import matplotlib.pyplot as plt
language = ['Python', 'Rust', 'Java', 'C#', 'Javascript']
precentage = [33.50, 15.30, 22.30, 12.45, 16.45]
plt.pie(
precentage,
labels = language,
autopct = '%1.2f%%', # format the numeric values in wedges
counterclock = False, # wedges plot direction
startangle = 90 # starting angle
)
plt.title('Language Popularity')
plt.show()
![]() |
Pie chart |
Conclusion
In this article, we show you how to draw simple graphs using the Matplotlib
library. Matplotlib is a very flexible option for creating graphs in
python.
References
- Matplotlib documentation - https://matplotlib.org/stable/
No comments:
Post a Comment