Unit 5: Data Visualization

CAP776 — Programming In Python 9 min read

I. Orientation — Visual communication with Python

Data visualization converts structured data into graphical forms so that patterns, comparisons, distributions, relationships, and unusual values can be recognized efficiently. Python commonly uses Matplotlib as a general plotting foundation and Seaborn as a higher-level statistical visualization library.

  • Data mapping: Variables are mapped to visual properties such as position, length, color, size, and shape.
  • Axes and scale: The x-axis and y-axis provide coordinate systems; labels, units, and suitable limits are essential for interpretation.
  • Chart selection: The data question determines the plot: trends use lines, category comparisons use bars, relationships use scatter plots, and distributions use histograms or box plots.
  • Accuracy: A graph should represent values proportionally and should not hide relevant variation through misleading scales or excessive decoration.
  • Python workflow: Data are commonly prepared with lists, NumPy arrays, or pandas DataFrames, then plotted with Matplotlib or Seaborn.
  • Figure structure: A figure is the complete canvas; an axes object is an individual plotting area within that figure.

II. Matplotlib — The foundational plotting library

Matplotlib is a Python library for creating static, animated, and interactive visualizations. Its object-oriented interface represents a figure containing one or more axes, while the pyplot interface provides convenient plotting commands.

A. Introduction to Matplotlib

This subsection establishes the basic Matplotlib workflow: import the library, provide data, customize the axes, and display or save the result.

  • Import convention: Matplotlib’s plotting interface is normally imported as plt.
PYTHON
  import matplotlib.pyplot as plt
  • Basic process: plt.plot(x, y) creates a graph, plt.xlabel() and plt.ylabel() identify variables, and plt.show() renders it.
  • Data requirement: If x = [1, 2, 3] and y = [2, 4, 6], Matplotlib pairs corresponding values to form points (1, 2), (2, 4), and (3, 6).
  • Output control: plt.savefig("sales.png", dpi=300, bbox_inches="tight") saves a high-resolution image with reduced unnecessary margins.
  • Object-oriented form: fig, ax = plt.subplots() explicitly creates a figure and axes, making complex visualizations easier to manage.

B. Line plots

A line plot connects ordered observations and is primarily used to show change over a continuous or sequential variable such as time.

  • Construction: ax.plot(months, sales, marker="o", color="navy", label="Sales") connects each month’s sales value.
  • Interpretation: The slope indicates direction and rate of change; an upward segment shows increase, while a downward segment shows decrease.
  • Labels and legend: ax.set_xlabel("Month"), ax.set_ylabel("Units sold"), and ax.legend() make multiple series distinguishable.
  • Multiple series: Plotting revenue and cost against the same time values enables direct comparison, but colors and labels must remain clear.
  • Limitation: Connecting unrelated categories can falsely suggest continuity; a line plot is inappropriate when the x-values have no meaningful order.

C. Bar charts

A bar chart compares numerical values across discrete categories, with bar length or height representing magnitude.

  • Vertical bars: ax.bar(["A", "B", "C"], [12, 19, 9]) compares three categories using their heights.
  • Horizontal bars: ax.barh(categories, values) is useful when category names are long.
  • Comparison principle: Bars should normally begin at zero because bar length represents quantity; a truncated baseline can exaggerate differences.
  • Grouped bars: Separate bars placed at each category compare groups such as product sales in 2023 and 2024.
  • Categorical order: Categories may be arranged alphabetically, chronologically, or by value, but the chosen ordering should support the intended comparison.

D. Scatter plots

A scatter plot displays paired numerical observations as individual points to investigate relationships, clusters, and outliers.

  • Construction: ax.scatter(hours, scores, alpha=0.7) places one point for each (hours, score) pair.
  • Association: An upward pattern suggests positive association; a downward pattern suggests negative association; a shapeless cloud suggests weak linear association.
  • Additional variables: The c argument can encode color and s can encode marker size, such as coloring points by region.
  • Outliers: A point far from the main cluster may indicate an unusual observation, measurement error, or a meaningful special case.
  • Causation warning: Correlation in a scatter plot does not prove that one variable causes the other.

E. Pie charts

A pie chart represents parts of a whole using sectors whose angles are proportional to category values.

  • Proportion formula: For category value (v_i) and total (T), its sector angle is:
TEXT
  angle_i = (v_i / T) × 360°
  • Construction: ax.pie([40, 35, 25], labels=["A", "B", "C"], autopct="%1.1f%%") displays percentages for three categories.
  • Use condition: Values should be non-negative and categories should represent mutually exclusive parts of the same total.
  • Readability: Pie charts work best with a small number of clearly different proportions; many similar sectors are difficult to compare.
  • Alternative: A bar chart usually supports more precise comparison, especially when exact differences matter.

F. Box-and-whisker plots

A box-and-whisker plot summarizes a numerical distribution through its quartiles, median, spread, and possible outliers.

  • Five-number structure: The plot displays minimum or lower whisker, first quartile (Q_1), median (Q_2), third quartile (Q_3), and maximum or upper whisker.
  • Interquartile range: The central spread is:
TEXT
  IQR = Q3 − Q1
  • Outlier rule: A common rule flags values below (Q_1 - 1.5(IQR)) or above (Q_3 + 1.5(IQR)).
  • Construction: ax.boxplot(values) creates a compact distribution summary.
  • Comparison: Side-by-side box plots compare groups using median position, IQR width, skewness, and outlier frequency.
  • Limitation: The plot does not show every observation or the detailed shape of multimodal distributions.

G. Histograms

A histogram groups continuous numerical values into intervals called bins and displays the frequency or density in each interval.

  • Construction: ax.hist(ages, bins=10, edgecolor="black") counts observations in ten intervals.
  • Bin effect: Too few bins can conceal structure; too many bins can make random fluctuations appear important.
  • Frequency versus density: Frequency shows counts, while density=True scales the total area of the bars to approximately 1.
  • Distribution features: Shape can reveal symmetry, skewness, gaps, peaks, and possible outliers.
  • Difference from bars: Histogram bars represent adjacent numerical intervals and usually touch; bar-chart bars represent separate categories and are often separated.

H. Multiple subplots in one figure

Multiple subplots place related graphs in one figure so that patterns can be compared using consistent data or scales.

  • Creation: fig, axes = plt.subplots(2, 2, figsize=(10, 7)) creates four axes arranged in two rows and two columns.
  • Accessing axes: axes[0, 0].plot(x, y) draws in the upper-left subplot; each axes object has independent labels and content.
  • Spacing: fig.tight_layout() reduces overlap between titles, labels, and tick marks.
  • Shared scales: sharex=True or sharey=True makes comparisons more reliable when variables use the same units.
  • Design principle: Each subplot should answer a related question; unnecessary panels increase cognitive load rather than insight.

III. Seaborn — Statistical visualization with DataFrames

Seaborn is a high-level Python visualization library built on Matplotlib. It uses attractive defaults and integrates naturally with pandas DataFrames, making statistical patterns easier to express.

A. Introduction to Seaborn

Seaborn provides concise functions for relational, categorical, and distributional graphics while retaining access to Matplotlib customization.

  • Import convention: The standard alias is sns.
PYTHON
  import seaborn as sns
  import matplotlib.pyplot as plt
  • Data orientation: A DataFrame with columns such as species, bill_length, and body_mass can be supplied using column names.
  • Themes: sns.set_theme(style="whitegrid") applies a consistent background, grid, font, and color configuration.
  • Statistical focus: Functions can show confidence intervals, regression fits, distributions, and category summaries rather than only raw marks.
  • Example: sns.scatterplot(data=df, x="bill_length", y="body_mass", hue="species") maps species to color automatically.

B. Seaborn versus Matplotlib

Both libraries create Python visualizations, but they differ in abstraction level, default behavior, and typical use.

  • Matplotlib strength: It offers precise control over individual artists, axes, annotations, coordinates, and unusual layouts.
  • Seaborn strength: It provides concise statistical plots, polished defaults, semantic mappings, and easy DataFrame integration.
  • Data input: Matplotlib commonly receives arrays such as x and y; Seaborn can directly interpret DataFrame columns through data, x, y, hue, and col.
  • Relationship: Seaborn uses Matplotlib underneath, so a Seaborn graph can be further customized with Matplotlib commands.
  • Choice principle: Use Seaborn for rapid exploratory and statistical analysis; use Matplotlib when exact, publication-specific layout control is required.

C. Data visualization using Seaborn

Seaborn supports several plot families that connect visual form with analytical purpose.

  • Relational plots: sns.lineplot() shows trends, while sns.scatterplot() shows relationships between numerical variables.
  • Categorical plots: sns.barplot(data=df, x="department", y="salary") displays an estimated category statistic, commonly the mean, with an uncertainty interval.
  • Distribution plots: sns.histplot(data=df, x="age", bins=15, kde=True) combines a histogram with a smoothed kernel density estimate.
  • Box and violin plots: sns.boxplot(data=df, x="group", y="score") compares quartiles; sns.violinplot() additionally displays distribution density.
  • Pairwise exploration: sns.pairplot(df, hue="species") produces scatter plots for variable pairs and distributions along the diagonal.
  • Faceting: sns.relplot(data=df, x="date", y="value", col="region", kind="line") creates one related panel for each region.

IV. Dashboard tools — Combining visualizations for decisions

A. Introduction to data visualization tools for creating dashboards

Dashboard tools combine charts, filters, indicators, and tables into an interactive interface that supports monitoring and decision-making.

  • Dashboard purpose: A sales dashboard might show total revenue, monthly trend, regional comparison, and product distribution in one screen.
  • Python options: Streamlit enables fast Python-based applications; Plotly Dash provides component-based web dashboards; Voilà can present notebooks as applications.
  • Interactive elements: Dropdowns, sliders, date selectors, and clickable legends allow users to filter data without rewriting code.
  • Architecture: A dashboard usually contains data loading, transformation, visualization, layout, and callback or event logic.
  • Design principles: Place key indicators first, use consistent units and colors, provide informative titles, and avoid overcrowding.
  • Limitations: Dashboards require data validation, responsive layout design, performance management, and careful control of misleading interactions or inaccessible color schemes.