Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Grouped Bars | Bar Charts
Visualization in Python with matplotlib
course content

Course Content

Visualization in Python with matplotlib

Visualization in Python with matplotlib

1. Basics: Line Charts
2. Bar Charts
3. Scatter Plots

bookGrouped Bars

Instead of placing each new bar above the previous one, there is one more approach to visualize such data: placing bars on the sides of other bars. We call such bar charts grouped bar charts.

The approach of building grouped bars is similar, but with some nuances. First, we need to predefine column widths. Then, we need to generate a sequence of 'positions' (preferably by using np.arange()). Then, with every call of the .bar() function we pass the newly created sequence as the first argument, and the values as the second. The third positional argument should be the column width. Then, for better readability, we should set the label parameter.

Note

To build 2 columns, we need to set x - width/2 as the first parameter with the first .bar() call, and x + width/2 for the second. If we want to build three columns, we can use the following approach: x - width, x, and x + width.

1234567891011121314151617181920212223242526
# Import library import matplotlib.pyplot as plt import numpy as np # Create data for chart countries = ['United States', 'India', 'Brazil'] agricultural = [333600, 1458996, 214368] industrial = [3722590, 2179020, 672336] services = [15592000, 5826510, 2361296] x = np.arange(len(countries)) width = 0.3 # column width # Create Axes and Figure objects fig, ax = plt.subplots() # Initialize bar chart ax.bar(x - 0.3, agricultural, width, label = 'Agricultural') ax.bar(x, industrial, width, label = 'Industrial') ax.bar(x + 0.3, services, width, label = 'Services') # Set custom ticks plt.xticks(x, countries) # Display the plot plt.legend() plt.show()
copy

We may see, that there we created a numpy array length of the same as countries, and then used approach from the note above. Also, we used the plt.xticks function to display countries on the x-axis ticks.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 5
some-alt