Matplotlib Bar Chart
To visualize value associated with categorical data in the bar format use matplotlib bar chart plt.bar() or plt.barh() methods.
Importing Libary to Plot Bar Chart
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style
Importing Data set to plot Bar Chart
This dataset of “Indian Artificial Intelligence Production Class” (IAIP). Instead of it use your business dataset.
# Dataset of 'Indian Artificial Intelligence Production (IAIP) Class"
#classes = ["Python", "R", "Artificial Intelligence", "Machine Learning", "Data Science"]
classes = ["Python", "R", "AI", "ML", "DS"]
class1_students = [30, 10, 20, 25, 10] # out of 100 student in each class
class2_students = [40, 5, 20, 20, 10]
class3_students = [35, 5, 30, 15, 15]
Plot Bar Chart with a different way
To plot bar chart using the matplotlib python library, use plt.bar() or plt.barh() methods.
Syntax: plt.bar(
x,
height,
width=0.8,
bottom=None,
*,
align=’center’,
data=None,
**kwargs,
)
Parameters
———-
x : sequence of scalars
height : scalar or sequence of scalars
width : scalar or array-like, optional …….(default: 0.8).
bottom : scalar or array-like, optional
align : {‘center’, ‘edge’}, optional, ……….default: ‘center’
Other Parameters
—————-
color : scalar or array-like, optional
edgecolor : scalar or array-like, optional
linewidth : scalar or array-like, optional
tick_label : string or array-like, optional ……. name of Bar
xerr, yerr : scalar or array-like of shape(N,) or shape(2,N), optional
ecolor : scalar or array-like, optional, default: ‘black’
capsize : scalar, optional
error_kw : dict, optional
log : bool, optional, default: False
orientation : {‘vertical’, ‘horizontal’}, optional
See also
——–
barh: Plot a horizontal bar plot.
Other optional kwargs:
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
===== alpha: float or None
animated: bool
antialiased: unknown
capstyle: {‘butt’, ’round’, ‘projecting’}
clip_box: `.Bbox`
clip_on: bool
clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
===== color: color
contains: callable
===== edgecolor: color or None or ‘auto’
===== facecolor: color or None
===== figure: `.Figure`
fill: bool
gid: str
hatch: {‘/’, ‘\\’, ‘|’, ‘-‘, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’}
in_layout: bool
joinstyle: {‘miter’, ’round’, ‘bevel’}
===== label: object
===== linestyle: {‘-‘, ‘–‘, ‘-.’, ‘:’, ”, (offset, on-off-seq), …}
===== linewidth: float or None for default
path_effects: `.AbstractPathEffect`
picker: None or bool or float or callable
rasterized: bool or None
sketch_params: (scale: float, length: float, randomness: float)
snap: bool or None
transform: `.Transform`
url: str
===== visible: bool
zorder: float
plt.bar(classes, class1_students) # Plot vertical Bar Chart
Output >>>
plt.barh(classes, class1_students) # Plot horizontal bar chart
Output >>>
Use multiple parameters of plt.bar() method
plt.bar(classes, class1_students, width = 0.2, align = "edge", color = "y",
edgecolor = "m", linewidth = 5, alpha = 0.9, linestyle = "--",
label =" Class 1 Students", visible=False)
#visible = True ## bar Chart will hide
Output >>>
Increase figure size and use style.
style.use("ggplot")
plt.figure(figsize=(16,9)) # figure size with ratio 16:9
plt.bar(classes, class1_students, width = 0.6, align = "edge", color = "k",
edgecolor = "m", linewidth = 5, alpha = 0.9, linestyle = "--",
label =" Class 1 Students") #visible=False
Output >>>
Plot horizontal bar chart with the above specification.
plt.figure(figsize=(16,9))
plt.barh(classes, class1_students, align = "edge", color = "k",
edgecolor = "m", linewidth = 5, alpha = 0.9, linestyle = "--",
label =" Class 1 Students") #visible=False
Output >>>
Decorating bar chart using multiple functions.
plt.figure(figsize=(16,9))
plt.bar(classes, class1_students, width = 0.6, align = "edge", color = "k",
edgecolor = "m", linewidth = 5, alpha = 0.9, linestyle = "--",
label =" Class 1 Students") #visible=False
plt.title("Bar Chart of IAIP Class", fontsize = 18)
plt.xlabel("Classes",fontsize = 15)
plt.ylabel("No. of Students", fontsize = 15)
plt.show()
Output >>>
Trying to plot two bar charts with a different dataset.
plt.figure(figsize=(16,9))
plt.bar(classes, class1_students, width = 0.2, color = "b",
label =" Class 1 Students") #visible=False
plt.bar(classes, class2_students, width = 0.2, color = "g",
label =" Class 2 Students")
plt.title("Bar Chart of IAIP Class", fontsize = 18)
plt.xlabel("Classes",fontsize = 15)
plt.ylabel("No. of Students", fontsize = 15)
plt.show()
Output >>>
The above code not generating two bar charts in one figure but they are overlapping. So use the below code to plot multiple bar charts. In below chart plot three bar charts using three different datasets.
plt.figure(figsize=(16,9))
classes_index = np.arange(len(classes))
width = 0.2
plt.bar(classes_index, class1_students, width , color = "b",
label =" Class 1 Students") #visible=False
plt.bar(classes_index + width, class2_students, width , color = "g",
label =" Class 2 Students")
plt.bar(classes_index + width + width, class3_students, width , color = "y",
label =" Class 2 Students")
plt.xticks(classes_index + width, classes, rotation = 20)
plt.title("Bar Chart of IAIP Class", fontsize = 18)
plt.xlabel("Classes",fontsize = 15)
plt.ylabel("No. of Students", fontsize = 15)
plt.show()
Output >>>
Plot Matplotlib Horizontal bar chart with the above specification.
plt.figure(figsize=(16,9))
classes_index = np.arange(len(classes))
width = 0.2
plt.barh(classes_index, class1_students, width , color = "b",
label =" Class 1 Students") #visible=False
plt.barh(classes_index + width, class2_students, width , color = "g",
label =" Class 2 Students")
plt.barh(classes_index + width + width, class3_students, width , color = "y",
label =" Class 3 Students")
plt.yticks(classes_index + width, classes, rotation = 20)
plt.title("Bar Chart of IAIP Class", fontsize = 18)
plt.ylabel("Classes",fontsize = 15)
plt.xlabel("No. of Students", fontsize = 15)
plt.legend()
plt.show()
Output >>>
Conclusion
In the matplotlib bar chart blog, we learn how to plot one and multiple bar charts with a real-time example using plt.bar() and plt.barh() methods. Along with that used different method and different parameter. We suggest you make your hand dirty with each and every parameter of the above methods. This is the best coding practice. After completion of the matplotlib tutorial jump on Seaborn.
Download Jupyter file of matplotlib bar chart source code
Visit to the official site of matplotlib.org
# Use multiple parameters of plt.bar() method
plt.bar(classes, class1_students, width = 0.2, align = “edge”, color = “y”,edgecolor = “m”, linewidth = 5, alpha = 0.9, linestyle = “–“,label =” Class 1 Students”, visible=True)
#visible = True ## bar Chart will be shown
Instead of #visible = True ## bar Chart will hide