A bar chart is used to display categorical data using rectangular bars with lengths/heights proportional to the values they represent. In this tutorial, we’ll look at how to plot a bar chart in python with matplotlib through some examples.
How to plot a bar chart in python?
Matplotlib is a visualization library in python offering a number of chart options to display your data. To plot a bar chart you can use matplotlib pyplot’s bar()
function. The following is the syntax:
import matplotlib.pyplot as plt
plt.bar(x, height)
Here, x
is the sequence of x-coordinates (or labels) to be used and height
is the sequence of heights for each x. There are a number of other parameters as well that help you customize the plot. For instance, you can change the width of the bars with the width
parameter or change the color of the bars using the color
parameter, etc. (see the examples below):
Examples
Let’s look at some examples of creating a bar chart with matplotlib.
1. Bar chart with default parameters
Let’s say you want to plot a bar chart of the number of championship victories of five of the most celebrated NBA players. Let’s create a bar chart by passing only the names and championship counts and keeping all other parameters as default.
import matplotlib.pyplot as plt
# NBA championship counts
players = ['Kobe Bryant', 'LeBron James', 'Michael Jordan',
'Larry Bird', 'Bill Russell']
titles = [5,4,6,3,11]
# plot a bar chart
plt.bar(players, titles)
plt.show()
Output:
We get a neat bar graph with the height of the bars representing the championship victories. Let’s add some basic formatting to this chart like axis labels and title to make it more clear.
import matplotlib.pyplot as plt
# NBA championship counts
players = ['Kobe Bryant', 'LeBron James', 'Michael Jordan',
'Larry Bird', 'Bill Russell']
titles = [5,4,6,3,11]
# plot a bar chart
plt.bar(players, titles)
# set axis labels
plt.ylabel("Rings")
# set chart title
plt.title("Championship Victories of NBA greats")
plt.show()
Output:
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
Note that we didn’t add labels to the x-axis as it’s pretty clear that it represents the names of NBA players.
2. Bar chart with custom width of bars
You can customize the width of the bars using the width parameter which takes either a scaler (if you want the same width for all bars) or a sequence of scalers depicting the width of each bar. By default, it is 0.8, so, pass a smaller value if you want to decrease the width or a larger value if you want to increase the width.
import matplotlib.pyplot as plt
# NBA championship counts
players = ['Kobe Bryant', 'LeBron James', 'Michael Jordan',
'Larry Bird', 'Bill Russell']
titles = [5,4,6,3,11]
# plot a bar chart
plt.bar(players, titles, width=0.6)
# set axis labels
plt.ylabel("Rings")
# set chart title
plt.title("Championship Victories of NBA greats")
plt.show()
Output:
You can see the bars here are comparatively thinner than the ones in the previous example since we passed 0.6, a value smaller than the default width of 0.8
3. Bar chart with custom colors
You can customize the bar color when plotting with the bar()
function by using the color
parameter. For instance, if you want the bars to be colored purple:
import matplotlib.pyplot as plt
# NBA championship counts
players = ['Kobe Bryant', 'LeBron James', 'Michael Jordan',
'Larry Bird', 'Bill Russell']
titles = [5,4,6,3,11]
# plot a bar chart
plt.bar(players, titles, color='purple')
# set axis labels
plt.ylabel("Rings")
# set chart title
plt.title("Championship Victories of NBA greats")
plt.show()
Output:
You can also specify a different color for each bar by passing the respective colors as a sequence to the color
parameter.
import matplotlib.pyplot as plt
# NBA championship counts
players = ['Kobe Bryant', 'LeBron James', 'Michael Jordan',
'Larry Bird', 'Bill Russell']
titles = [5,4,6,3,11]
colors = ['gold', 'gold', 'red', 'green', 'green']
# plot a bar chart
plt.bar(players, titles, color=colors)
# set axis labels
plt.ylabel("Rings")
# set chart title
plt.title("Championship Victories of NBA greats")
plt.show()
Output:
4. Bar chart with sorted bars
To plot a bar chart with the bars in sorted order you need to sort your data before passing it to the bar()
function. For instance, to show a bar chart in ascending order of championship wins:
import matplotlib.pyplot as plt
# NBA championship counts
players = ['Kobe Bryant', 'LeBron James', 'Michael Jordan',
'Larry Bird', 'Bill Russell']
titles = [5,4,6,3,11]
# Sort the lists
titles_ordered = sorted(titles)
players_ordered = [x for _, x in sorted(zip(titles, players))]
# plot a bar chart
plt.bar(players_ordered, titles_ordered)
# set axis labels
plt.ylabel("Rings")
# set chart title
plt.title("Championship Victories of NBA greats")
plt.show()
Output:
In the above example, you can see that we first sort the title counts and then sort the names corresponding to the sorted titles. The sorted lists are saved as separate lists which are then passed to the bar()
function.
For more on plotting bar chart with matplotlib’s bar()
function refer to its documentation.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having matplotlib version 3.2.2
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Tutorials on matplotlib –
- Change Background Color of Plot in Matplotlib
- Change Font Size of elements in a Matplotlib plot
- Matplotlib – Save Plot as a File
- Change Size of Figures in Matplotlib
- Plot a Bar Chart using Matplotlib
- Plot a Pie Chart with Matplotlib
- Plot Histogram in Python using Matplotlib
- Create a Scatter Plot in Python with Matplotlib
- Plot a Line Chart in Python with Matplotlib
- Save Matplotlib Plot with Transparent Background
- Change Font Type in Matplotlib plots