Turning Data Into Decisions
Bar charts, histograms, scatter plots, subplots, and plotting straight from pandas
In the previous session, we covered the fundamentals of Matplotlib: creating a figure, styling it, and saving plots. We learned how to draw a line, representing trends over time. But the work of an analyst rarely stops at time-series data. To truly derive value, you need to compare discrete categories, understand the distribution of your data, identify relationships between variables, and present multiple views of your data simultaneously. This session dives into those essential visualization techniques.
Let's grab a coffee and transform raw numbers into charts that tell a compelling story.
1. Bar Charts: Comparing Categories
When to use a bar chart
Bar charts are your primary tool when you need to compare discrete categories against each other. Think regions, products, departments, or months. If the question is "which one is bigger?" or "how do these compare?", a bar chart provides an immediate, clear answer. The length of each bar is proportional to the value it represents, making direct comparisons intuitive.
Creating a basic bar chart
Matplotlib's `pyplot` module offers the `bar()` function for vertical bars and `barh()` for horizontal bars. You provide the positions for the bars on one axis and the corresponding values (heights/widths) on the other. For categorical data, you'll typically use integers for positions and then set the tick labels to your category names.
For instance, to compare sales figures across different regions, you might have region names as categories and sales numbers as values. The `bar()` function would plot these, with the x-axis showing region names and the y-axis showing sales volume.
Customizing bar charts
Beyond basic plotting, you can customize bar charts extensively. This includes changing bar colors, adding edge colors, adjusting bar width, and stacking bars to show sub-categories within each main category. For example, if you're comparing product sales across regions, you could stack bars to show the contribution of different product lines within each region's total sales. This adds another layer of analytical depth.
2. Histograms: Understanding Distributions
When to use a histogram
Histograms are crucial for understanding the distribution of a single numerical variable. Unlike bar charts that compare discrete categories, histograms group continuous data into bins and show the frequency of data points falling into each bin. This helps you identify the shape of the distribution (e.g., normal, skewed, bimodal), detect outliers, and understand the central tendency and spread of your data.
Creating a histogram
The `pyplot.hist()` function is used here. You pass it an array of numerical data. Matplotlib automatically calculates bin ranges and counts the occurrences within each bin. You can specify the number of bins or the bin edges manually to fine-tune the visualization.
Consider a dataset of customer ages. A histogram would reveal how many customers fall into age brackets like 18-25, 26-35, and so on, showing whether your customer base is younger, older, or evenly distributed.
Interpreting histograms
The shape of a histogram is informative. A symmetrical, bell-shaped histogram suggests a normal distribution. A histogram skewed to the right indicates a long tail of higher values, while a left skew indicates a tail of lower values. Peaks in the histogram represent modes in the data. Understanding these shapes is fundamental to statistical analysis and model building.
3. Scatter Plots: Spotting Relationships
When to use a scatter plot
Scatter plots are designed to visualize the relationship between two numerical variables. Each point on the plot represents a single data observation, with its position determined by the values of the two variables on the x and y axes. They are invaluable for identifying correlations (positive, negative, or none), detecting patterns, and spotting clusters or outliers in multivariate data.
Creating a scatter plot
Matplotlib's `pyplot.scatter()` function is used for this. You provide two arrays of equal length, one for the x-axis values and one for the y-axis values. Each corresponding pair of values (x[i], y[i]) forms a point on the plot.
For example, plotting advertising spending against sales revenue for different products could reveal if increased ad spend correlates with higher sales. A tight cluster of points trending upwards would suggest a strong positive correlation.
Enhancing scatter plots
Scatter plots can be enhanced by varying point size, color, and marker style. This allows you to encode a third or even fourth variable. For instance, you could plot 'advertising spend' vs. 'sales revenue', with point size representing 'marketing budget' and point color representing 'product category'. This turns a simple two-variable plot into a rich, multi-dimensional data exploration tool.
4. Subplots: Multiple Views, One Figure
When to use subplots
Often, you need to present several related plots together for comparison or to show different facets of the same data. Subplots allow you to create a grid of smaller charts within a single larger figure. This is far more effective than creating and displaying multiple independent figures, especially when you want to highlight how different views of the data relate to each other.
Creating subplots
Matplotlib's `pyplot.subplots()` function is the standard way to create a figure and a set of subplots. It returns a figure object and an array of axes objects. You specify the number of rows and columns for your grid (e.g., `plt.subplots(2, 2)` for a 2x2 grid). You can then plot on each individual axes object.
Imagine analyzing customer data: you might use a 2x2 grid to show a histogram of customer ages, a bar chart of customer demographics by region, a scatter plot of purchase frequency vs. average order value, and a line chart of sales over time, all within one cohesive visualization.

Managing subplot layouts
When creating subplots, managing spacing and labels is key. `plt.tight_layout()` is a lifesaver, automatically adjusting subplot parameters to give a tight layout and prevent labels from overlapping. You can also manually control spacing and add a super title to the entire figure for context.
5. Plotting Directly from Pandas
Leveraging Pandas' plotting capabilities
Pandas DataFrames and Series have built-in plotting methods that leverage Matplotlib behind the scenes. This offers a highly convenient way to generate common plots directly from your data structures. Instead of explicitly importing `matplotlib.pyplot`, you can often call methods like `.plot()`, `.hist()`, or `.scatter()` directly on your DataFrame or Series.
Common Pandas plotting methods
DataFrame.plot(): A general-purpose plotting function that can create line plots, bar plots, scatter plots, and more, based on specified `kind` arguments.DataFrame.hist(): Generates histograms for each numerical column in the DataFrame.DataFrame.plot.scatter(): Specifically for creating scatter plots, allowing you to map columns to x and y axes, and optionally to color and size.DataFrame.plot.bar()andDataFrame.plot.barh(): For creating bar charts.
This integration streamlines the data exploration workflow. You can load data into a Pandas DataFrame, perform initial cleaning and manipulation, and then immediately start visualizing without context switching between libraries.
For example, after loading sales data into a DataFrame `df`, you could quickly visualize sales by region with `df.plot(kind='bar', x='Region', y='Sales')` or visualize the distribution of order values with `df['OrderValue'].hist()`. This direct plotting capability makes Matplotlib accessible and efficient for everyday data analysis tasks.
