Hello! Welcome back to our course.
In our last lesson, we created a choropleth map to visualize the single most popular movie in each country. This gave us a fantastic global overview, but it has its limitations. For instance, it's difficult to compare the popularity of the #2 or #3 movies, or to see how a selection of countries compares on a common set of films.
Today, we will address that by focusing on our next learning outcome: to generate comparative bar charts to visualize top movie preferences for selected countries. This method is perfect for a more detailed, side-by-side analysis. We'll explore why grouped bar charts are the right tool, how to prepare your data for them, and how to create them using Python.
1. Why a Comparative Bar Chart?
A bar chart is one of the most fundamental visualization types, used to compare numerical values across different categories. As you learned with the choropleth map, choosing the right chart for your data and your question is critical.
A grouped bar chart (also called a multiple bar chart) is a powerful extension of the basic bar chart. It allows you to introduce a second categorical variable.
- Main Category: The primary groups you want to compare (e.g.,
country). - Sub-Category: The divisions within each primary group (e.g.,
movie_title).
This is exactly what we need: to compare movie preferences (sub-category) for a few selected countries (main category).
Multiple Bar Chart | Grouped Bar Graph | Matplotlib | Python Tutorials
To see what a grouped bar chart looks like and how it differs from other types, let's watch the first part of this video from Amulya's Academy.
Please watch from the beginning to 01:36. The video introduces the concept of a multiple bar graph and contrasts it with a stacked bar graph, which is a useful distinction.
As the video showed, instead of stacking bars on top of each other, we place them side-by-side. This makes direct comparison of the sub-categories (the movies) across the main categories (the countries) much easier.
2. The Key Step: Reshaping Your Data
The secret to creating a grouped bar chart easily in pandas is to have your data in the correct shape. Visualization libraries like pandas.plot or Seaborn expect data in a "wide" format for this task.
- Long Format: The format our data is likely in now. Each row is a single observation (e.g., one movie's view count in one country).
- Wide Format: The format we need. The index of the DataFrame represents our main categories (countries), the columns represent our sub-categories (movies), and the cells contain the values (view counts).
Let's assume after filtering and aggregating, we have a "long" DataFrame of the top 2 movies for the USA and the UK:
import pandas as pd
# Sample 'long' format data
data = {
'country': ['USA', 'USA', 'UK', 'UK'],
'movie_title': ['Elf', 'Home Alone', 'Love Actually', 'The Grinch'],
'view_count': [100, 80, 90, 85]
}
long_df = pd.DataFrame(data)
print(long_df)
Output:
country movie_title view_count
0 USA Elf 100
1 USA Home Alone 80
2 UK Love Actually 90
3 UK The Grinch 85
To transform this into a "wide" format, we use the pivot_table() method. This is a fundamental skill in data manipulation, especially for engineers working with data.
wide_df = long_df.pivot_table(
index='country',
columns='movie_title',
values='view_count'
)
print(wide_df)
Output:
movie_title Elf Home Alone Love Actually The Grinch
country
UK NaN NaN 90.0 85.0
USA 100.0 80.0 NaN NaN
Notice how the country values became the index, the movie_title values became the new columns, and NaN (Not a Number) fills the gaps where a movie didn't appear for a country. This wide_df is now perfectly structured for plotting.
How to make grouped bar charts in pandas/Python with crosstab and pivot tables and more
This concept of reshaping data is so important that it's worth seeing it explained by an expert. This video from Jonathan Soma provides an excellent, clear walkthrough of using pivot_table to prepare data for a grouped bar chart.
Please watch from 06:51 to 13:05. The example uses dog breeds and boroughs, but the principle is identical to our movies and countries. Focus on how pivot_table is used to make the index and columns ready for plotting.
Test your understanding!
You have the following "long" DataFrame named french_german_trends:
| country | movie_title | view_count |
|---|---|---|
| France | Le Père Noël est une ordure | 120 |
| France | Love Actually | 75 |
| Germany | Drei Haselnüsse für Aschenbrödel | 110 |
| Germany | The Grinch | 80 |
Write the single line of pandas code to pivot this DataFrame into a "wide" format suitable for a grouped bar chart, with countries as the index.
Show answer
wide_trends = french_german_trends.pivot_table(index='country', columns='movie_title', values='view_count')
This correctly pivots the DataFrame, setting up country as the main grouping axis (the index) and movie_title as the sub-groups (the columns).
3. Creating the Grouped Bar Chart
With our data properly shaped, the plotting itself becomes surprisingly simple. We'll look at two common approaches in Python.
Method 1: The Direct pandas Approach
Because you have your data in a pandas DataFrame, the most direct way to plot is using the built-in .plot() functionality, which uses matplotlib under the hood.
Python Bar Plot: Master Basic and More Advanced ...
The DataCamp tutorial 'Python Bar Plot' provides excellent, concise code examples for various libraries. We'll look at how it implements grouped bar plots using pandas.
Please read the section titled 'Grouped and stacked bar plots' under the 'Creating bar plots with Pandas' heading. Focus on the code for the 'Grouped Bar Plot' and see how simple it is once the data is pivoted.
Applying this to our wide_df from before:
import matplotlib.pyplot as plt
# Assuming wide_df is our pivoted DataFrame
# We'll fill NaN values with 0 so they don't cause plotting issues
wide_df = wide_df.fillna(0)
# Create the plot
ax = wide_df.plot.bar(rot=0) # rot=0 keeps the x-axis labels horizontal
# Add labels and title for clarity
ax.set_ylabel('View Count')
ax.set_xlabel('Country')
ax.set_title('Top Movie Preferences in the USA and UK')
plt.legend(title='Movie Title')
plt.show()
This code will produce a grouped bar chart where 'UK' and 'USA' are the groups on the x-axis, and each has bars representing the view counts for the different movies.
Method 2: The matplotlib Approach (for More Control)
Sometimes you need more fine-grained control over the plot than the direct pandas method offers. In this case, you can use matplotlib directly. This requires a bit more work, as you have to calculate the position for each bar manually. Your background in applied mathematics should make the logic behind the coordinate manipulation feel familiar.
Python Bar Plot: Master Basic and More Advanced ...
Let's return to the DataCamp tutorial to see a clean implementation of a grouped bar plot using Matplotlib and NumPy.
Read the section 'Grouped and stacked bar plots' under the 'Creating bar plots with Matplotlib' heading. Pay close attention to how np.arange is used to set the initial bar positions and how bar_width is used to offset the bars for each group.
The core logic, as shown in the article, involves these steps:
- Define the positions for the groups on the x-axis (e.g.,
[0, 1]for UK and USA). - Define the width of the bars.
- For each sub-category (movie), plot its bars by adding an offset to the base positions. For two sub-categories, you might plot at
x - width/2andx + width/2. For three, you might usex - width,x, andx + width. - Finally, set the x-tick labels back to the country names at the center of each group.
This method is more verbose but gives you complete authority over every element of the plot.
4. Best Practices for Effective Bar Charts
A chart that is technically correct can still be confusing if poorly designed. Here are some key principles to ensure your comparisons are clear and honest.
- Start the Value Axis at Zero: A bar chart's power comes from comparing the lengths of the bars. Starting the axis at a non-zero value can exaggerate differences and mislead the viewer.
- Logical Ordering: If your categories don't have a natural order, consider sorting the bars (e.g., from highest to lowest) to make comparison easier. For grouped charts, you could order the main categories (countries) by the value of their most popular movie.
- Use Color Purposefully: Don't let your plotting library choose a distracting rainbow of colors. Use a limited palette. A great strategy is to assign a specific, consistent color to each movie title across all your project's charts.
- Horizontal vs. Vertical: If your category labels (movie titles in the legend, or country names on the axis) are long, a horizontal bar chart (
.plot.barh()) can prevent them from overlapping and becoming unreadable.
These guidelines, drawn from resources like the "A Complete Guide to Bar Charts" from Atlassian, are crucial for professional-quality data storytelling.
Conclusion
Today, we've added a vital visualization tool to our toolkit. You've learned how to move beyond a high-level map to create detailed, comparative bar charts.
Key Takeaways:
- Grouped bar charts are ideal for comparing a numerical value across sub-categories (movies) within several main categories (countries).
- The most important step is data preparation. Transforming your data from a "long" to a "wide" format using
pandas.pivot_table()is essential. - You can create these charts using the high-level
pandas.plot.bar()for speed or the lower-levelmatplotliblibrary for fine-grained control. - Effective chart design, including proper ordering, labeling, and use of color, is crucial for clear communication.
In our next and final lesson of this module, we'll tackle a new challenge: what if you want to compare the popularity of many movies across many countries simultaneously? A bar chart would become cluttered. To solve this, we will learn how to create a heatmap to compare movie popularity across multiple countries, a perfect visualization for matrix-like data.