1. Home
  2. Explore
  3. Computer Science
  4. Data Visualization with Python

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Data Visualization with Python

Data Visualization with Python (using Matplotlib)

Importance of Data Visualization

Data visualization is the art of representing raw data in the form of beautiful and aesthetic graphs.

Working with a huge dataset containing thousands of columns and millions of rows makes it extremely difficult to find meaningful insights by looking at raw numbers alone. Data visualization transforms this raw data into visual representations that reveal interesting patterns quickly.

For example, a dataset about prehistoric animals can be represented through images of a mammoth and a saber-tooth cat. From such an image, one can instantly see:

  • Mammoth: size 13,000 lbs, low aggressiveness, speed 25 km/h

  • Saber-tooth cat: size 400 lbs, high aggressiveness, speed 75 km/h

Anscombe's Quartet

A classic demonstration of why visualization matters is Anscombe's quartet — four datasets that have nearly identical summary statistics (mean, variance, correlation) but look completely different when plotted.

Statistic

File 1

File 2

File 3

File 4

Mean of x

9.0

9.0

9.0

9.0

Mean of y

7.5

7.5

7.5

7.5

Std dev of x

3.16

3.16

3.16

3.16

Std dev of y

1.94

1.94

1.94

1.94

Correlation

0.82

0.82

0.82

0.82

If one only looked at these numbers, they would assume the four datasets are nearly identical. However, when each dataset is plotted, the relationships between x and y are very different — one is linear, another is curved, one has an outlier, and one is a vertical line with one outlier. Data visualization alone reveals these critical differences.


Getting Started with Matplotlib

Python provides several visualization libraries, including Matplotlib, GGPlot, Plotly, Bokeh, Seaborn, and others. This session focuses on Matplotlib, the most widely used library.

To begin, import the necessary packages:

import matplotlib.pyplot as plt
import numpy as np

In Jupyter Notebook, these imports make all plotting commands available.


Line Plots

A line plot shows the relationship between two continuous variables by connecting data points with straight lines.

Basic Line Plot

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.show()

Customizing a Line Plot

  • Change line color: use the color parameter, e.g., color='red'

  • Add a title: plt.title('Line Plot')

  • Add axis labels: plt.xlabel('X-axis') and plt.ylabel('Y-axis')

plt.plot(x, y, color='red')
plt.title('Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

Subplots (Multiple Plots in One Figure)

Use plt.subplot(nrows, ncols, index) to create two or more plots side by side.

# First subplot
plt.subplot(1, 2, 1)  # 1 row, 2 columns, activate first plot
y1 = 2 * np.array(x) + 5
plt.plot(x, y1)

# Second subplot
plt.subplot(1, 2, 2)  # activate second plot
y2 = 3 * np.array(x) + 10
plt.plot(x, y2)

plt.show()

This creates two line plots in the same figure, each with different slopes and intercepts.


Bar Plots

A bar plot is used for categorical data — it compares quantities across different categories.

Creating a Bar Plot

Example using a dictionary of fruits and their quantities:

fruit = {'Apple': 30, 'Mango': 45, 'Banana': 10}
names = list(fruit.keys())
quantity = list(fruit.values())

plt.bar(names, quantity)
plt.show()

The x-axis shows fruit names, the y-axis shows quantity. The plot immediately shows that mangoes have the highest count and bananas the lowest.

Customizing a Bar Plot

  • Title: plt.title('Distribution of Fruits')

  • Axis labels: plt.xlabel('Fruits'), plt.ylabel('Quantity')

  • Bar color: color='orange'

Horizontal Bar Plot

Use plt.barh(names, quantity) to create a horizontal bar chart — the only difference from a vertical bar plot.


Scatter Plots

A scatter plot displays the relationship between two numerical variables using individual points. Use plt.scatter(x, y).

Basic Scatter Plot

x = [10, 20, 30, 40, 50, 60, 70]
a = [1, 3, 5, 7, 9, 11, 13]
b = [2, 4, 6, 8, 10, 12, 14]
plt.scatter(x, a)
plt.scatter(x, b)
plt.xlabel('X')
plt.ylabel('A and B')
plt.show()

Customizing Scatter Plots

  • Point size: parameter s (e.g., s=200)

  • Marker shape: parameter marker (e.g., marker=1 for tilted upward arrow, marker=2 for downward arrow, or use standard markers like 'o', '^', 's')

  • Figure size: use plt.figure(figsize=(width, height)) before the plot

plt.figure(figsize=(10, 10))
plt.scatter(x, a, s=200, marker=1)
plt.scatter(x, b, s=500, marker=2)
plt.show()

Histograms

A histogram shows the distribution of a single numerical variable by grouping data into bins and displaying the frequency of each bin. Unlike a bar plot, a histogram deals with continuous numerical data, not categories.

Basic Histogram

data = [1, 1, 1, 7, 5, 4, 3, 1, 1, 5, 9]
plt.hist(data)
plt.show()

The histogram reveals that the value 1 appears most frequently, followed by 3 and 5. Gaps indicate values with zero frequency (e.g., 8 is missing).

Histogram on a Real Dataset (Iris)

import pandas as pd
iris = pd.read_csv('iris.csv')
plt.hist(iris['sepal length'])
plt.show()

This shows the distribution of sepal lengths: most flowers have sepal lengths between 5 and 6.5, very few above 6.5, and nearly none at length 8.

Customizing Histograms

  • Color: color='red'

  • Number of bins: bins=30 (or bins=50 for finer granularity)

plt.hist(iris['sepal length'], color='red', bins=50)
plt.show()

Box Plots

A box plot (or box-and-whisker plot) provides a five-number summary: minimum, first quartile, median, third quartile, and maximum. It also highlights outliers.

Creating a Box Plot

data1 = [1,2,3,4,5,6,7,8,9]
data2 = [1,2,3,4,5,4,3,2,1]
data3 = [6,7,8,9,8,7,6,5,4]
data = [data1, data2, data3]
plt.boxplot(data)
plt.show()
  • Median is the line inside each box.

  • The box spans the interquartile range (Q1 to Q3).

  • Whiskers extend to the minimum and maximum within 1.5*IQR.

From the example:

  • Data1: median=5, values range 1–9, wide distribution.

  • Data2: median=3, values range 1–5, narrower distribution.

  • Data3: median=7, values range 4–9.


Violin Plots

A violin plot is similar to a box plot but also shows the probability density of the data at different values. It looks like a violin — wider where data is more dense.

plt.violinplot(data)
plt.show()

Customizing Violin Plots

  • Show median line: showmedians=True

  • Show mean line: showmeans=True

  • Add grid: plt.grid(True)

  • Add title and axis labels as usual.

plt.title('Distribution of Data')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.violinplot(data, showmedians=True, showmeans=True)
plt.grid(True)
plt.show()

Observe that for symmetric distributions, the mean and median may be the same value.


Pie Charts and Donut Plots

A pie chart displays parts of a whole — proportions of categories. A donut plot is a pie chart with a hole in the center.

Basic Pie Chart

fruits = ['Apple', 'Mango', 'Orange', 'Grapes']
quantity = [30, 45, 12, 100]
plt.pie(quantity, labels=fruits)
plt.show()

Customizing Pie Charts

  • Percentages: autopct='%0.1f%%' adds percentage labels (e.g., 53.5% grapes, 6.4% oranges)

  • Shadow: shadow=True

  • Explode (highlight a slice): explode=[0,0,0,0.1] — offsets the fourth slice by 0.1 radius

  • Colors: colors=['black','gray','yellow','green'] — provide a list of colors matching the number of slices.

plt.pie(quantity, labels=fruits, autopct='%0.1f%%', shadow=True, explode=[0,0,0,0.1])
plt.show()

Creating a Donut Plot

A donut plot is made by overlaying two pie charts:

  1. The outer pie chart (the actual data) with a larger radius.

  2. An inner white pie chart (a circle) with a smaller radius to create the hole.

# Outer pie
pie1 = plt.pie(quantity, labels=fruits, radius=2)

# Inner white circle
pie2 = plt.pie([5], colors=['white'], radius=1)  # [5] just a dummy value

plt.show()

To add another concentric ring (e.g., a third inner circle), create a third pie chart with an even smaller radius and a different color:

pie1 = plt.pie(quantity, labels=fruits, radius=2)
pie2 = plt.pie([5], colors=['white'], radius=1)
pie3 = plt.pie([5], colors=['blue'], radius=0.5)
plt.show()

The key is that the radius of each inner circle must be smaller than the one outside it.


Area Plots

An area plot (or stack plot) shows the distribution of numerical data over a range, often used to display how a quantity accumulates.

Creating an Area Plot

x = [10, 20, 30, 40, 50, 60, 70, 80, 90]
y = [1, 1, 2, 5, 6, 4, 7, 4, 6]
plt.stackplot(x, y)
plt.show()

The area under the curve is filled, making it easy to see where values are higher (larger area) or lower. This is similar in spirit to a histogram but shows the actual shape of the distribution over the x-axis.

Adding a Line on Top of an Area Plot

plt.stackplot(x, y)
plt.plot(x, y, color='green')
plt.show()

This overlays a green line on the filled area, combining the visual emphasis of the area with the precision of a line.


Summary of Plot Types

Plot Type

Purpose

Data Type

Line Plot

Show trends over continuous x (e.g., time)

Numerical x and y

Bar Plot

Compare quantities across categories

Categorical x, numerical y

Scatter Plot

Show relationship between two numerical variables

Two numerical variables

Histogram

Show distribution of a single numerical variable

One numerical variable

Box Plot

Show statistical summary (median, quartiles, outliers)

One or more numerical variables

Violin Plot

Show distribution density + summary statistics

One or more numerical variables

Pie Chart

Show proportions of a whole

Categorical with numerical values

Donut Plot

Same as pie but with a hole

Same as pie

Area Plot

Show distribution or accumulation over x

Numerical x and y

Key Difference: Bar Plot vs. Histogram

  • Bar plot is for categorical data (e.g., fruit names).

  • Histogram is for numerical data (e.g., sepal length).


Additional Customizations (Q&A Highlights)

Changing Colors in a Pie Chart

Use the colors parameter with a list of color strings. The list must have the same number of elements as slices. Example: colors=['black', 'gray', 'yellow', 'green'].

Adding a Line Plot on Top of an Area Plot

After plt.stackplot(x, y), simply call plt.plot(x, y, color='green'). This draws a line over the filled area.

Creating a Third Inner Ring in a Donut Plot

Add a third plt.pie with a radius smaller than the previous inner circle. For example, radius=0.5 inside radius=1 inside radius=2, each with different colors. The inner circles must have dummy data (e.g., [5]) and the same number of elements.


This session covered the fundamental plot types in Matplotlib. Understanding when to use each type and how to customize them is essential for effective data visualization. Experimenting with real datasets (like the iris dataset) builds hands-on skills for extracting insights from data.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent