etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Python Matplotlib Bar Plot

In this article, you will learn about Python Matplotlib Bar Plot.

Bar plot represents data in rectangular bar with heights proportional to the values that they represent. It is used to compare things between different groups or to track changes over time. It shows the relationship between a numeric and a categorical variable. It can also display values for several levels of grouping. The bars can be plotted vertically or horizontally. The bar graphs are best when the big changes in data over time. Matplotlib provides bar() method to plot bar graph.

Syntax of Bar Plot

matplotlib.pyplot.bar(x, height, width, bottom, align)

x - It specifies the sequence of scalars. The x coordinates of bar.
height - It specifies scalar or sequence of scalars. The height of the bars.
width (optional)- The width of the bars(by default 0.8).
bottom (optional)- The y coordinate(s) of the bars bases.
align (optional)- Alignment of the bars to the x coordinates.



Basic Example of Bar Graph

Here is a very basic bar plot -

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar([1, 2, 3, 4, 5, 6], [4, 3, 7, 9, 5, 2])
plt.show()

The above code returns the following output -

Matplotlib Bar Plot

Bar Plot Horizontally

The barh() function is used to make a horizontal bar plot. The bars are positioned at y with the given alignment. Here is a simple example that plots the temperature of different cities -

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
city = ['Dhanbad', 'Bokaro', 'Ranchi', 'Koderma', 'Giridih']
temp = [35,37,32,33,38]
ax.barh(city,temp,0.3)
plt.show()
Matplotlib Horizontal Bar Plot



Set Label Name, Title & Color of the Bar Plot

The above bar plots are very basic. So, in the given example, you will learn to add the label name, title of the plot and to set the color of the bar. Here, we have also used the ggplot style sheet. The ggplot is a plotting system for Python based on R's ggplot2 and the Grammar of Graphics. It is built for making professional looking and to plot quickly with minimal code.

import matplotlib.pyplot as plt
plt.style.use('ggplot')

city = ['Dhanbad', 'Bokaro', 'Ranchi', 'Koderma', 'Giridih']
temp = [35,37,32,33,38]

x_pos = [i for i, _ in enumerate(city)]

plt.bar(city,temp,0.3,color='red')

plt.ylabel("Temperature")
plt.xlabel("City")
plt.title("Temperature of Jhar Popular Cities")
plt.show()
Matplotlib ggplot

Multiple Bar Plot

A multiple bar plot is a plot that has multiple bars for each category. In this, we can compare as many sets of data you want. The process for creating a multiple bar graph is same as creating any other bar graph, only will have to set different colors to represent different sets of data.

import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')

state = ['Delhi', 'MP', 'UP', 'Tamil', 'Assam']
women_champion = [35,37,32,33,38]
men_champion = [30,22,40,42,35]

inv = np.arange(5)

x_pos = [i for i, _ in enumerate(state)]

plt.bar(inv,women_champion,0.25,color='red')
plt.bar(inv + 0.25,men_champion,0.25,color='blue')

plt.ylabel("Champions")
plt.xlabel("States")
plt.title("Champions of Different States")
plt.xticks(inv + 0.25 / 2, state)
plt.show()

The above code returns the following output -

Matplotlib Multiple Bar Plot



Matplotlib Stacked Bar Chart

A stacked bar chart is a visual representation of data. It uses the length of two or more stacked bars to represent the components of a total quantitative value across a range of different categorical values. Here is a very simple example of a stacked bar chart -

import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')

state = ['Delhi', 'MP', 'UP', 'Tamil', 'Assam']
gold_champion =  np.array([32, 15, 12, 29, 25])
silver_champion = np.array([35, 20, 28, 21, 10])
bronze_champion = np.array([40, 35, 29, 10, 27])

inv = np.arange(5)

inv = [i for i, _ in enumerate(state)]

plt.bar(inv,gold_champion,0.25,color='red',bottom=silver_champion+bronze_champion)
plt.bar(inv,silver_champion,0.25,color='blue',bottom=bronze_champion)
plt.bar(inv,bronze_champion,0.25,color='green')

plt.ylabel("Champions")
plt.xlabel("States")
plt.title("Champions of Different States")
plt.xticks(inv, state)
plt.show()

The output of this code is shown in the following image -

Matplotlib Multiple Stacked Bar Plot



Related Articles

How to capture a video in Python OpenCV and save
Python OpenCV Overlaying or Blending Two Images
Contour Detection using Python OpenCV
Harris Corner Detection using Python OpenCV
Human Body Detection Program In Python OpenCV
Face Recognition OpenCV Source Code
Canny Edge Detector OpenCV Python
Python NumPy: Overview and Examples
Image processing using Python Pillow
Python OpenCV Histogram Equalization
Python OpenCV Histogram of Color Image
Python OpenCV Histogram of Grayscale Image
Python OpenCV Image Filtering
Python OpenCV ColorMap
Python OpenCV Gaussian Blur Filtering
Python OpenCV Overview and Examples




Most Popular Development Resources
Characteristics of a Good Computer Program
-----------------
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP Create Word Document from HTML
-----------------
PHP code to send email using SMTP
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Simple pagination in PHP with MySQL
-----------------
Fibonacci Series Program in PHP
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to add multiple custom markers on google map
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
Php file based authentication
-----------------
PHP Secure User Registration with Login/logout
-----------------
jQuery File upload progress bar with file size validation
-----------------
Polling system using PHP, Ajax and MySql
-----------------
Simple PHP File Cache
-----------------
SQL Injection Prevention Techniques
-----------------
Simple File Upload Script in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP User Authentication by IP Address
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
How to generate QR Code in PHP
-----------------
Calculate the distance between two locations using PHP
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Detect Mobile Devices in PHP
-----------------
Set and Get Cookies in PHP
-----------------
To check whether a year is a leap year or not in php
-----------------
PHP Server Side Form Validation
-----------------
Date Timestamp Formats in PHP
-----------------
Get Visitor\'s location and TimeZone
-----------------
Simple Show Hide Menu Navigation
-----------------
Convert MySQL to JSON using PHP
-----------------
PHP Programming Error Types
-----------------
PHP Sending HTML form data to an Email
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
How to print specific part of a web page in javascript
-----------------
Google Street View API Example
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
PHP Getting Document of Remote Address
-----------------
PHP Connection and File Handling on FTP Server
-----------------
File Upload Validation in PHP
-----------------
R Plot Types
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 27

    Best AI Startups In India

    Artificial Intelligence is a process of making an intelligent computer machine that does tasks intelligently...

  • Jan 23

    Most in demand programming languages for 2019

    In this article, we have mentioned the analyzed results of the most in demand programming language for 2019...

  • Jan 15

    Web Robots

    Web robots is an internet robot or simply crawlers, or spiders and do not relate this with hardware robots...

  • Jan 12

    Most in demand NoSQL databases software for 2019

    In this article, we have mentioned the analyzed result of most in demand NoSQL database softwares for 2019...

  • Jan 10

    Kotlin : Android App Development Choice

    Kotlin is a general-purpose open-source programming language. It runs on the JVM and its syntax is much like Java...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2021. All Rights Reserved.