Skip to content

Chapter 4 of 7

Data Visualization with Matplotlib and Seaborn

Matplotlib is the workhorse plotting library underlying most Python visualization. A basic line plot is created with plt.plot(x, y) followed by plt.show(). Before displaying, you can annotate the figure using plt.title('Title'), plt.xlabel('X'), and plt.ylabel('Y'). Other common plot types include plt.bar(categories, values) for vertical bar charts, plt.scatter(x, y) for individual data points, and plt.hist(data, bins=20) for histograms that show the distribution of a single variable across a chosen number of bins.

For more sophisticated statistical graphics, Seaborn builds on Matplotlib with higher-level functions. A correlation matrix can be visualized as a heatmap with sns.heatmap(df.corr(), annot=True, cmap='coolwarm'), where the color encoding and the optional numerical annotations make relationships between variables easy to read. sns.countplot(x='category', data=df) shows the number of observations within each category as bars, and sns.pairplot(df) generates a grid of scatter plots for every pair of numeric columns, with histograms along the diagonal for individual distributions.

Both libraries support layouts of multiple plots side by side. Calling fig, axes = plt.subplots(1, 2, figsize=(10, 4)) creates a figure with one row and two columns of axes that you can populate individually. Once a figure is ready, plt.savefig('plot.png', dpi=300, bbox_inches='tight') saves it to disk, with dpi controlling resolution and bbox_inches='tight' trimming excess whitespace. In Jupyter notebooks, running %matplotlib inline at the top of a notebook ensures that plots are rendered directly below the code cell, making exploration and storytelling both interactive and reproducible.

All chapters
  1. 1NumPy Essentials
  2. 2Pandas DataFrames and Selection
  3. 3Data Cleaning and Type Handling
  4. 4Data Visualization with Matplotlib and Seaborn
  5. 5Aggregation, Merging, and Reshaping
  6. 6Feature Engineering and Preprocessing
  7. 7Data Inspection and Jupyter Productivity

Drill it

Reading is not remembering. These come from the Python For Data Science deck:

Q

What function creates a NumPy array from a Python list?

np.array([1, 2, 3]) converts a Python list into a NumPy ndarray.

Q

How do you create a 1D array of zeros with 5 elements in NumPy?

np.zeros(5) returns array([0., 0., 0., 0., 0.]).

Q

How do you create a 3x3 identity matrix in NumPy?

np.eye(3) returns a 3×3 array with ones on the diagonal and zeros elsewhere.

Q

What does <code>np.arange(0, 10, 2)</code> return?

It returns array([0, 2, 4, 6, 8]) — values from 0 up to (not including) 10 with step 2.