AI summary by TwinMind
Lecture 25: Plotting
MIT OpenCourseWare
1h 17m 54s
Matplotlib Library Introduction
- Final 2 lectures of course, no more deliverables after tonight
- Focus on matplotlib plotting library for data visualization
- Import statement:
import matplotlib.pyplot as pltpltis alias to avoid typing full name repeatedly- Can use any alias name (e.g.,
as Anna)
- Matplotlib is most basic plotting library, others build upon it
- Other libraries add features like interactive hover, but basic one sufficient for learning
Basic Plotting Concepts
- Need X values and Y values as separate lists
- Index-by-index correspondence creates coordinate points
- Lists must be same length or Python throws error
- Plot displays in new window (interactive) or inline in console
- Toggle via Tools → Preferences → IPython Console → Graphics
- Python automatically fits data within frame with wiggle room
- Order of points matters - consecutive points connected by lines
Plot vs Scatter
plt.plot()connects points with linesplt.scatter()plots individual points without connecting- Scatter useful when data points are out of order
- Example: out-of-order temperature data creates messy connected plot
Multiple Lines on One Figure
- Sequential plot commands add to same figure
- No need to explicitly create new figure
- Python automatically frames to fit all data
- Can cause scaling issues when data ranges vary greatly (e.g., exponential vs linear)
Creating Multiple Figures
plt.figure(name)creates new window with specified name- If figure with same name exists, brings to foreground
- Subsequent plot commands add to current active figure
- Example: separate windows for exponential, linear, quadratic, cubic plots
Real Data Example - Monthly Temperatures
- X-axis: months (range 1-12), Y-axis: temperature list
- Basic plot shows data but lacks context
- Essential additions:
plt.title()for descriptive titleplt.xlabel()andplt.ylabel()for axis labelsplt.xlim()to set axis limits (removed wiggle room)plt.xticks()to control tick marks- Second parameter for
plt.xticks()provides custom labels (month names vs numbers)
Multi-City Temperature Comparison
- Plot multiple cities on same figure
labelparameter in plot command for legend entriesplt.legend(loc='best')adds legend, Python chooses optimal location- Can specify legend location manually
Plot Customization
Line Styles and Colors
- Shorthand notation:
'b-'(blue solid),'r--'(red dashed),'g-.'(green dash-dot) - Explicit parameters:
color='b',linestyle='-' - Available colors: b, g, r, c, m, y, k, plus RGB/hex values
- Line styles: solid (-), dashed (--), dotted (:), dash-dot (-.)
Markers and Line Width
- Markers show individual data points:
'.'(dot),'o'(circle), triangle, square options linewidthparameter controls line thickness- Legend automatically reflects chosen styles
Subplots
- Create multiple plots in single window
plt.subplot(rows, cols, position)- Position numbering: 1, 2, 3, 4... (reading order)
- Example:
plt.subplot(2, 1, 1)creates 2 rows, 1 column, selects top position - Important: set consistent axis limits for comparison (
plt.ylim(0, 100)) - Empty positions remain blank
US Population Data Analysis
- Data file: 40 years (1610-2010), every 10 years
- File format: year, space, population (with commas)
- Data processing challenges:
- Remove commas from population numbers
- Convert strings to integers
- Split on spaces to separate year from population
- Code technique: keep only digits and spaces, then split
Linear vs Logarithmic Scale
- Linear scale: shows war impacts (WWII bump, Civil War dip)
- Logarithmic scale (
plt.yscale('log')): reveals exponential growth patterns - Different visualizations provide different insights
- Early years show faster growth rate than later years (visible only on log scale)
Country Population Analysis
- 237 countries ranked by population
- Tab-separated file format: rank, country, population, date
- Extract only population values for analysis
- Same comma removal technique required
Benford's Law Discovery
- Analysis of first digits from all country populations
- Extract first digit:
int(str(population)[0]) - Histogram shows surprising non-uniform distribution
- Results: ~30% start with 1, ~18% with 2, decreasing to ~5% with 9
- Benford's Law: P(first digit = d) = log₁₀(1 + 1/d)
- Applies to many natural datasets: social media followers, stock prices, income taxes
- Fraud detection application: fake numbers don't follow Benford's Law
Multi-City Temperature Analysis
- Dataset: 55 years × 21 cities × 365 days = ~420,000 data points
- File format: city, temperature (Celsius), date (YYYYMMDD)
- Convert Celsius to Fahrenheit for analysis
Average Temperature Comparison
- One data point per city (average over all years/days)
- Scatter plot shows expected results: cold vs warm cities
- Limited insight from simple averages
Temperature Trends Over Time
- Annual averages for each city over 55 years
- Boston: slight increase, San Diego: steady, Phoenix: dramatic increase, Miami: slight increase
- Reveals climate change patterns in different regions
Temperature Extremes Analysis
- Plot minimum, maximum, average for each year
- Set consistent Y-axis limits (0-100°F) for comparison
- Reveals variation differences between cities
- Boston: high variation (0-90°F), San Diego: low variation (40-80°F)
- Boston average ≈ Miami/San Diego minimum temperatures
Temperature Distribution Analysis
- Histogram of daily temperatures for specific years
- 365 days binned by temperature value
- 1961 vs 2015 comparison shows distribution shifts
- Boston: wide bell curve, possibly bimodal
- San Diego: narrower range, bimodal distribution (55°F and 70°F peaks)
- Transparency (alpha) parameter helps visualize overlapping data
- Alternative: separate subplots for clearer comparison
