A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axis of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories.
Creating a Horizontal bar plot
The matplotlib API in Python provides the barh() function which can be used in MATLAB style use or as an object-oriented API. The syntax of the barh() function to be used with the axes is as follows:-
Syntax: matplotlib.pyplot.barh(y, width, height=0.8, left=None, *, align=’center’, **kwargs)
Some of the positional and optional parameters of the above function are described below:
Parameters | Description |
Y | Co-ordinates of the Y bars. |
width | Scalar or array like, denotes the width of the bars. |
height | Scalar or array like, denotes the height of the bars(default value is 0.8). |
left | Scalar or sequence of scalars, denotes X co-ordinates on the left sides of the bars(default value is 0). |
align | {‘center’, ‘edge’}aligns the base of the Y co-ordinates(default value is center). |
color | Scalar or array like, denotes the color of the bars. |
edgecolor | Scalar or array like, denotes the edge color of the bars. |
linewidth | Scalar or array like, denotes the width of the bar edges. |
tick_label | Scalar or array like, denotes the tick labels of the bars(default value is None). |
The function creates a horizontal bar plot bounded with a rectangle depending on the given parameters. Following is a simple example of the barh() method to create a horizontal bar plot, which represents the number of students enrolled in different courses of an institute.
Example 1:
Python3
import numpy as np import matplotlib.pyplot as plt # creating the dataset data = { 'C' : 20 , 'C++' : 15 , 'Java' : 30 , 'Python' : 35 } courses = list (data.keys()) values = list (data.values()) fig = plt.figure(figsize = ( 10 , 5 )) # creating the bar plot plt.barh(courses, values, color = 'maroon' ) plt.xlabel( "Courses offered" ) plt.ylabel( "No. of students enrolled" ) plt.title( "Students enrolled in different courses" ) plt.show() |
Output :
Here plt.barh(courses, values, color=’maroon’) is used to specify that the bar chart is to be plotted by using the courses column as the Y-axis, and the values as the X-axis. The color attribute is used to set the color of the bars(maroon in this case).plt.xlabel(“Courses offered”) and plt.ylabel(“students enrolled”) are used to label the corresponding axes.plt.title() is used to make a title for the graph.plt.show() is used to show the graph as output using the previous commands.
Example 2:
Python3
import pandas as pd from matplotlib import pyplot as plt # Read CSV into pandas data = pd.read_csv(r "Downloads/cars1.csv" ) data.head() df = pd.DataFrame(data) name = df[ 'car' ].head( 12 ) price = df[ 'price' ].head( 12 ) # Figure Size fig, ax = plt.subplots(figsize = ( 16 , 9 )) # Horizontal Bar Plot ax.barh(name, price) # Remove axes splines for s in [ 'top' , 'bottom' , 'left' , 'right' ]: ax.splines[s].set_visible( False ) # Remove x, y Ticks ax.xaxis.set_ticks_position( 'none' ) ax.yaxis.set_ticks_position( 'none' ) # Add padding between axes and labels ax.xaxis.set_tick_params(pad = 5 ) ax.yaxis.set_tick_params(pad = 10 ) # Add x, y gridlines ax.grid(b = True , color = 'grey' , linestyle = '-.' , linewidth = 0.5 , alpha = 0.2 ) # Show top values ax.invert_yaxis() # Add annotation to bars for i in ax.patches: plt.text(i.get_width() + 0.2 , i.get_y() + 0.5 , str ( round ((i.get_width()), 2 )), fontsize = 10 , fontweight = 'bold' , color = 'grey' ) # Add Plot Title ax.set_title( 'Sports car and their price in crore' , loc = 'left' , ) # Add Text watermark fig.text( 0.9 , 0.15 , 'Jeeteshgavande30' , fontsize = 12 , color = 'grey' , ha = 'right' , va = 'bottom' , alpha = 0.7 ) # Show Plot plt.show() |
Output: