diff-diff 2.3.2__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1676 @@
1
+ """
2
+ Visualization functions for difference-in-differences analysis.
3
+
4
+ Provides event study plots and other diagnostic visualizations.
5
+ """
6
+
7
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ if TYPE_CHECKING:
13
+ from diff_diff.bacon import BaconDecompositionResults
14
+ from diff_diff.honest_did import HonestDiDResults, SensitivityResults
15
+ from diff_diff.power import PowerResults, SimulationPowerResults
16
+ from diff_diff.pretrends import PreTrendsPowerCurve, PreTrendsPowerResults
17
+ from diff_diff.results import MultiPeriodDiDResults
18
+ from diff_diff.staggered import CallawaySantAnnaResults
19
+ from diff_diff.imputation import ImputationDiDResults
20
+ from diff_diff.sun_abraham import SunAbrahamResults
21
+
22
+ # Type alias for results that can be plotted
23
+ PlottableResults = Union[
24
+ "MultiPeriodDiDResults",
25
+ "CallawaySantAnnaResults",
26
+ "SunAbrahamResults",
27
+ "ImputationDiDResults",
28
+ pd.DataFrame,
29
+ ]
30
+
31
+
32
+ def plot_event_study(
33
+ results: Optional[PlottableResults] = None,
34
+ *,
35
+ effects: Optional[Dict[Any, float]] = None,
36
+ se: Optional[Dict[Any, float]] = None,
37
+ periods: Optional[List[Any]] = None,
38
+ reference_period: Optional[Any] = None,
39
+ pre_periods: Optional[List[Any]] = None,
40
+ post_periods: Optional[List[Any]] = None,
41
+ alpha: float = 0.05,
42
+ figsize: Tuple[float, float] = (10, 6),
43
+ title: str = "Event Study",
44
+ xlabel: str = "Period Relative to Treatment",
45
+ ylabel: str = "Treatment Effect",
46
+ color: str = "#2563eb",
47
+ marker: str = "o",
48
+ markersize: int = 8,
49
+ linewidth: float = 1.5,
50
+ capsize: int = 4,
51
+ show_zero_line: bool = True,
52
+ show_reference_line: bool = True,
53
+ shade_pre: bool = True,
54
+ shade_color: str = "#f0f0f0",
55
+ ax: Optional[Any] = None,
56
+ show: bool = True,
57
+ ) -> Any:
58
+ """
59
+ Create an event study plot showing treatment effects over time.
60
+
61
+ This function creates a coefficient plot with point estimates and
62
+ confidence intervals for each time period, commonly used to visualize
63
+ dynamic treatment effects and assess pre-trends.
64
+
65
+ Parameters
66
+ ----------
67
+ results : MultiPeriodDiDResults, CallawaySantAnnaResults, or DataFrame, optional
68
+ Results object from MultiPeriodDiD, CallawaySantAnna, or a DataFrame
69
+ with columns 'period', 'effect', 'se' (and optionally 'conf_int_lower',
70
+ 'conf_int_upper'). If None, must provide effects and se directly.
71
+ effects : dict, optional
72
+ Dictionary mapping periods to effect estimates. Used if results is None.
73
+ se : dict, optional
74
+ Dictionary mapping periods to standard errors. Used if results is None.
75
+ periods : list, optional
76
+ List of periods to plot. If None, uses all periods from results.
77
+ reference_period : any, optional
78
+ The reference period to highlight. When explicitly provided, effects
79
+ are normalized (ref effect subtracted) and ref SE is set to NaN.
80
+ When None and auto-inferred from results, only hollow marker styling
81
+ is applied (no normalization). If None, tries to infer from results.
82
+ pre_periods : list, optional
83
+ List of pre-treatment periods. Used for shading.
84
+ post_periods : list, optional
85
+ List of post-treatment periods. Used for shading.
86
+ alpha : float, default=0.05
87
+ Significance level for confidence intervals.
88
+ figsize : tuple, default=(10, 6)
89
+ Figure size (width, height) in inches.
90
+ title : str, default="Event Study"
91
+ Plot title.
92
+ xlabel : str, default="Period Relative to Treatment"
93
+ X-axis label.
94
+ ylabel : str, default="Treatment Effect"
95
+ Y-axis label.
96
+ color : str, default="#2563eb"
97
+ Color for points and error bars.
98
+ marker : str, default="o"
99
+ Marker style for point estimates.
100
+ markersize : int, default=8
101
+ Size of markers.
102
+ linewidth : float, default=1.5
103
+ Width of error bar lines.
104
+ capsize : int, default=4
105
+ Size of error bar caps.
106
+ show_zero_line : bool, default=True
107
+ Whether to show a horizontal line at y=0.
108
+ show_reference_line : bool, default=True
109
+ Whether to show a vertical line at the reference period.
110
+ shade_pre : bool, default=True
111
+ Whether to shade the pre-treatment region.
112
+ shade_color : str, default="#f0f0f0"
113
+ Color for pre-treatment shading.
114
+ ax : matplotlib.axes.Axes, optional
115
+ Axes to plot on. If None, creates new figure.
116
+ show : bool, default=True
117
+ Whether to call plt.show() at the end.
118
+
119
+ Returns
120
+ -------
121
+ matplotlib.axes.Axes
122
+ The axes object containing the plot.
123
+
124
+ Examples
125
+ --------
126
+ Using with MultiPeriodDiD results:
127
+
128
+ >>> from diff_diff import MultiPeriodDiD, plot_event_study
129
+ >>> did = MultiPeriodDiD()
130
+ >>> results = did.fit(data, outcome='y', treatment='treated',
131
+ ... time='period', post_periods=[3, 4, 5])
132
+ >>> plot_event_study(results)
133
+
134
+ Using with a DataFrame:
135
+
136
+ >>> df = pd.DataFrame({
137
+ ... 'period': [-2, -1, 0, 1, 2],
138
+ ... 'effect': [0.1, 0.05, 0.0, 0.5, 0.6],
139
+ ... 'se': [0.1, 0.1, 0.0, 0.15, 0.15]
140
+ ... })
141
+ >>> plot_event_study(df, reference_period=0)
142
+
143
+ Using with manual effects:
144
+
145
+ >>> effects = {-2: 0.1, -1: 0.05, 0: 0.0, 1: 0.5, 2: 0.6}
146
+ >>> se = {-2: 0.1, -1: 0.1, 0: 0.0, 1: 0.15, 2: 0.15}
147
+ >>> plot_event_study(effects=effects, se=se, reference_period=0)
148
+
149
+ Notes
150
+ -----
151
+ Event study plots are a standard visualization in difference-in-differences
152
+ analysis. They show:
153
+
154
+ 1. **Pre-treatment periods**: Effects should be close to zero if parallel
155
+ trends holds. Large pre-treatment effects suggest the assumption may
156
+ be violated.
157
+
158
+ 2. **Reference period**: Usually the last pre-treatment period (t=-1).
159
+ When explicitly specified via ``reference_period``, effects are normalized
160
+ to zero at this period. When auto-inferred, shown with hollow marker only.
161
+
162
+ 3. **Post-treatment periods**: The treatment effects of interest. These
163
+ show how the outcome evolved after treatment.
164
+
165
+ The confidence intervals help assess statistical significance. Effects
166
+ whose CIs don't include zero are typically considered significant.
167
+ """
168
+ try:
169
+ import matplotlib.pyplot as plt
170
+ except ImportError:
171
+ raise ImportError(
172
+ "matplotlib is required for plotting. " "Install it with: pip install matplotlib"
173
+ )
174
+
175
+ from scipy import stats as scipy_stats
176
+
177
+ # Track if reference_period was explicitly provided by user
178
+ reference_period_explicit = reference_period is not None
179
+
180
+ # Extract data from results if provided
181
+ if results is not None:
182
+ extracted = _extract_plot_data(
183
+ results, periods, pre_periods, post_periods, reference_period
184
+ )
185
+ effects, se, periods, pre_periods, post_periods, reference_period, reference_inferred = (
186
+ extracted
187
+ )
188
+ # If reference was inferred from results, it was NOT explicitly provided
189
+ if reference_inferred:
190
+ reference_period_explicit = False
191
+ elif effects is None or se is None:
192
+ raise ValueError("Must provide either 'results' or both 'effects' and 'se'")
193
+
194
+ # Ensure effects and se are dicts
195
+ if not isinstance(effects, dict):
196
+ raise TypeError("effects must be a dictionary mapping periods to values")
197
+ if not isinstance(se, dict):
198
+ raise TypeError("se must be a dictionary mapping periods to values")
199
+
200
+ # Get periods to plot
201
+ if periods is None:
202
+ periods = sorted(effects.keys())
203
+
204
+ # Compute confidence intervals
205
+ critical_value = scipy_stats.norm.ppf(1 - alpha / 2)
206
+
207
+ # Normalize effects to reference period ONLY if explicitly specified by user
208
+ # Auto-inferred reference periods (from CallawaySantAnna) just get hollow marker styling,
209
+ # NO normalization. This prevents unintended normalization when the reference period
210
+ # isn't a true identifying constraint (e.g., CallawaySantAnna with base_period="varying").
211
+ if reference_period is not None and reference_period in effects and reference_period_explicit:
212
+ ref_effect = effects[reference_period]
213
+ if np.isfinite(ref_effect):
214
+ effects = {p: e - ref_effect for p, e in effects.items()}
215
+ # Set reference SE to NaN (it's now a constraint, not an estimate)
216
+ # This follows fixest convention where the omitted category has no SE/CI
217
+ se = {p: (np.nan if p == reference_period else s) for p, s in se.items()}
218
+
219
+ plot_data = []
220
+ for period in periods:
221
+ effect = effects.get(period, np.nan)
222
+ std_err = se.get(period, np.nan)
223
+
224
+ # Skip entries with NaN effect, but allow NaN SE (will plot without error bars)
225
+ if np.isnan(effect):
226
+ continue
227
+
228
+ # Compute CI only if SE is finite
229
+ if np.isfinite(std_err):
230
+ ci_lower = effect - critical_value * std_err
231
+ ci_upper = effect + critical_value * std_err
232
+ else:
233
+ ci_lower = np.nan
234
+ ci_upper = np.nan
235
+
236
+ plot_data.append(
237
+ {
238
+ "period": period,
239
+ "effect": effect,
240
+ "se": std_err,
241
+ "ci_lower": ci_lower,
242
+ "ci_upper": ci_upper,
243
+ "is_reference": period == reference_period,
244
+ }
245
+ )
246
+
247
+ if not plot_data:
248
+ raise ValueError("No valid data to plot")
249
+
250
+ df = pd.DataFrame(plot_data)
251
+
252
+ # Create figure if needed
253
+ if ax is None:
254
+ fig, ax = plt.subplots(figsize=figsize)
255
+ else:
256
+ fig = ax.get_figure()
257
+
258
+ # Convert periods to numeric for plotting
259
+ period_to_x = {p: i for i, p in enumerate(df["period"])}
260
+ x_vals = [period_to_x[p] for p in df["period"]]
261
+
262
+ # Shade pre-treatment region
263
+ if shade_pre and pre_periods is not None:
264
+ pre_x = [period_to_x[p] for p in pre_periods if p in period_to_x]
265
+ if pre_x:
266
+ ax.axvspan(min(pre_x) - 0.5, max(pre_x) + 0.5, color=shade_color, alpha=0.5, zorder=0)
267
+
268
+ # Draw horizontal zero line
269
+ if show_zero_line:
270
+ ax.axhline(y=0, color="gray", linestyle="--", linewidth=1, zorder=1)
271
+
272
+ # Draw vertical reference line
273
+ if show_reference_line and reference_period is not None:
274
+ if reference_period in period_to_x:
275
+ ref_x = period_to_x[reference_period]
276
+ ax.axvline(x=ref_x, color="gray", linestyle=":", linewidth=1, zorder=1)
277
+
278
+ # Plot error bars (only for entries with finite CI)
279
+ has_ci = df["ci_lower"].notna() & df["ci_upper"].notna()
280
+ if has_ci.any():
281
+ df_with_ci = df[has_ci]
282
+ x_with_ci = [period_to_x[p] for p in df_with_ci["period"]]
283
+ yerr = [
284
+ df_with_ci["effect"] - df_with_ci["ci_lower"],
285
+ df_with_ci["ci_upper"] - df_with_ci["effect"],
286
+ ]
287
+ ax.errorbar(
288
+ x_with_ci,
289
+ df_with_ci["effect"],
290
+ yerr=yerr,
291
+ fmt="none",
292
+ color=color,
293
+ capsize=capsize,
294
+ linewidth=linewidth,
295
+ capthick=linewidth,
296
+ zorder=2,
297
+ )
298
+
299
+ # Plot point estimates
300
+ for i, row in df.iterrows():
301
+ x = period_to_x[row["period"]]
302
+ if row["is_reference"]:
303
+ # Hollow marker for reference period
304
+ ax.plot(
305
+ x,
306
+ row["effect"],
307
+ marker=marker,
308
+ markersize=markersize,
309
+ markerfacecolor="white",
310
+ markeredgecolor=color,
311
+ markeredgewidth=2,
312
+ zorder=3,
313
+ )
314
+ else:
315
+ ax.plot(x, row["effect"], marker=marker, markersize=markersize, color=color, zorder=3)
316
+
317
+ # Set labels and title
318
+ ax.set_xlabel(xlabel)
319
+ ax.set_ylabel(ylabel)
320
+ ax.set_title(title)
321
+
322
+ # Set x-axis ticks
323
+ ax.set_xticks(x_vals)
324
+ ax.set_xticklabels([str(p) for p in df["period"]])
325
+
326
+ # Add grid
327
+ ax.grid(True, alpha=0.3, axis="y")
328
+
329
+ # Tight layout
330
+ fig.tight_layout()
331
+
332
+ if show:
333
+ plt.show()
334
+
335
+ return ax
336
+
337
+
338
+ def _extract_plot_data(
339
+ results: PlottableResults,
340
+ periods: Optional[List[Any]],
341
+ pre_periods: Optional[List[Any]],
342
+ post_periods: Optional[List[Any]],
343
+ reference_period: Optional[Any],
344
+ ) -> Tuple[Dict, Dict, List, List, List, Any, bool]:
345
+ """
346
+ Extract plotting data from various result types.
347
+
348
+ Returns
349
+ -------
350
+ tuple
351
+ (effects, se, periods, pre_periods, post_periods, reference_period, reference_inferred)
352
+
353
+ reference_inferred is True if reference_period was auto-detected from results
354
+ rather than explicitly provided by the user.
355
+ """
356
+ # Handle DataFrame input
357
+ if isinstance(results, pd.DataFrame):
358
+ if "period" not in results.columns:
359
+ raise ValueError("DataFrame must have 'period' column")
360
+ if "effect" not in results.columns:
361
+ raise ValueError("DataFrame must have 'effect' column")
362
+ if "se" not in results.columns:
363
+ raise ValueError("DataFrame must have 'se' column")
364
+
365
+ effects = dict(zip(results["period"], results["effect"]))
366
+ se = dict(zip(results["period"], results["se"]))
367
+
368
+ if periods is None:
369
+ periods = list(results["period"])
370
+
371
+ # DataFrame input: reference_period was already set by caller, never inferred here
372
+ return effects, se, periods, pre_periods, post_periods, reference_period, False
373
+
374
+ # Handle MultiPeriodDiDResults
375
+ if hasattr(results, "period_effects"):
376
+ effects = {}
377
+ se = {}
378
+
379
+ for period, pe in results.period_effects.items():
380
+ effects[period] = pe.effect
381
+ se[period] = pe.se
382
+
383
+ if pre_periods is None and hasattr(results, "pre_periods"):
384
+ pre_periods = results.pre_periods
385
+
386
+ if post_periods is None and hasattr(results, "post_periods"):
387
+ post_periods = results.post_periods
388
+
389
+ if periods is None:
390
+ periods = sorted(results.period_effects.keys())
391
+
392
+ # Auto-detect reference period from results if not explicitly provided
393
+ ref_inferred = False
394
+ if (
395
+ reference_period is None
396
+ and hasattr(results, "reference_period")
397
+ and results.reference_period is not None
398
+ ):
399
+ reference_period = results.reference_period
400
+ ref_inferred = True
401
+
402
+ return effects, se, periods, pre_periods, post_periods, reference_period, ref_inferred
403
+
404
+ # Handle CallawaySantAnnaResults (event study aggregation)
405
+ if hasattr(results, "event_study_effects") and results.event_study_effects is not None:
406
+ effects = {}
407
+ se = {}
408
+
409
+ for rel_period, effect_data in results.event_study_effects.items():
410
+ effects[rel_period] = effect_data["effect"]
411
+ se[rel_period] = effect_data["se"]
412
+
413
+ if periods is None:
414
+ periods = sorted(effects.keys())
415
+
416
+ # Track if reference_period was explicitly provided vs auto-inferred
417
+ reference_inferred = False
418
+
419
+ # Reference period is typically -1 for event study
420
+ if reference_period is None:
421
+ reference_inferred = True # We're about to infer it
422
+ # Detect reference period from n_groups=0 marker (normalization constraint)
423
+ # This handles anticipation > 0 where reference is at e = -1 - anticipation
424
+ for period, effect_data in results.event_study_effects.items():
425
+ if effect_data.get("n_groups", 1) == 0 or effect_data.get("n_obs", 1) == 0:
426
+ reference_period = period
427
+ break
428
+ # Fallback to -1 if no marker found (backward compatibility)
429
+ if reference_period is None:
430
+ reference_period = -1
431
+
432
+ if pre_periods is None:
433
+ pre_periods = [p for p in periods if p < 0]
434
+
435
+ if post_periods is None:
436
+ post_periods = [p for p in periods if p >= 0]
437
+
438
+ return effects, se, periods, pre_periods, post_periods, reference_period, reference_inferred
439
+
440
+ raise TypeError(
441
+ f"Cannot extract plot data from {type(results).__name__}. "
442
+ "Expected MultiPeriodDiDResults, CallawaySantAnnaResults, "
443
+ "SunAbrahamResults, ImputationDiDResults, or DataFrame."
444
+ )
445
+
446
+
447
+ def plot_group_effects(
448
+ results: "CallawaySantAnnaResults",
449
+ *,
450
+ groups: Optional[List[Any]] = None,
451
+ figsize: Tuple[float, float] = (10, 6),
452
+ title: str = "Treatment Effects by Cohort",
453
+ xlabel: str = "Time Period",
454
+ ylabel: str = "Treatment Effect",
455
+ alpha: float = 0.05,
456
+ show: bool = True,
457
+ ax: Optional[Any] = None,
458
+ ) -> Any:
459
+ """
460
+ Plot treatment effects by treatment cohort (group).
461
+
462
+ Parameters
463
+ ----------
464
+ results : CallawaySantAnnaResults
465
+ Results from CallawaySantAnna estimator.
466
+ groups : list, optional
467
+ List of groups (cohorts) to plot. If None, plots all groups.
468
+ figsize : tuple, default=(10, 6)
469
+ Figure size.
470
+ title : str
471
+ Plot title.
472
+ xlabel : str
473
+ X-axis label.
474
+ ylabel : str
475
+ Y-axis label.
476
+ alpha : float, default=0.05
477
+ Significance level for confidence intervals.
478
+ show : bool, default=True
479
+ Whether to call plt.show().
480
+ ax : matplotlib.axes.Axes, optional
481
+ Axes to plot on.
482
+
483
+ Returns
484
+ -------
485
+ matplotlib.axes.Axes
486
+ The axes object.
487
+ """
488
+ try:
489
+ import matplotlib.pyplot as plt
490
+ except ImportError:
491
+ raise ImportError(
492
+ "matplotlib is required for plotting. " "Install it with: pip install matplotlib"
493
+ )
494
+
495
+ from scipy import stats as scipy_stats
496
+
497
+ if not hasattr(results, "group_time_effects"):
498
+ raise TypeError("results must be a CallawaySantAnnaResults object")
499
+
500
+ # Get groups to plot
501
+ if groups is None:
502
+ groups = sorted(set(g for g, t in results.group_time_effects.keys()))
503
+
504
+ # Create figure
505
+ if ax is None:
506
+ fig, ax = plt.subplots(figsize=figsize)
507
+ else:
508
+ fig = ax.get_figure()
509
+
510
+ # Color palette
511
+ colors = plt.cm.tab10(np.linspace(0, 1, len(groups)))
512
+
513
+ critical_value = scipy_stats.norm.ppf(1 - alpha / 2)
514
+
515
+ for i, group in enumerate(groups):
516
+ # Get effects for this group
517
+ group_effects = [
518
+ (t, data) for (g, t), data in results.group_time_effects.items() if g == group
519
+ ]
520
+ group_effects.sort(key=lambda x: x[0])
521
+
522
+ if not group_effects:
523
+ continue
524
+
525
+ times = [t for t, _ in group_effects]
526
+ effects = [data["effect"] for _, data in group_effects]
527
+ ses = [data["se"] for _, data in group_effects]
528
+
529
+ yerr = [
530
+ [e - (e - critical_value * s) for e, s in zip(effects, ses)],
531
+ [(e + critical_value * s) - e for e, s in zip(effects, ses)],
532
+ ]
533
+
534
+ ax.errorbar(
535
+ times,
536
+ effects,
537
+ yerr=yerr,
538
+ label=f"Cohort {group}",
539
+ color=colors[i],
540
+ marker="o",
541
+ capsize=3,
542
+ linewidth=1.5,
543
+ )
544
+
545
+ ax.axhline(y=0, color="gray", linestyle="--", linewidth=1)
546
+ ax.set_xlabel(xlabel)
547
+ ax.set_ylabel(ylabel)
548
+ ax.set_title(title)
549
+ ax.legend(loc="best")
550
+ ax.grid(True, alpha=0.3, axis="y")
551
+
552
+ fig.tight_layout()
553
+
554
+ if show:
555
+ plt.show()
556
+
557
+ return ax
558
+
559
+
560
+ def plot_sensitivity(
561
+ sensitivity_results: "SensitivityResults",
562
+ *,
563
+ show_bounds: bool = True,
564
+ show_ci: bool = True,
565
+ breakdown_line: bool = True,
566
+ figsize: Tuple[float, float] = (10, 6),
567
+ title: str = "Honest DiD Sensitivity Analysis",
568
+ xlabel: str = "M (restriction parameter)",
569
+ ylabel: str = "Treatment Effect",
570
+ bounds_color: str = "#2563eb",
571
+ bounds_alpha: float = 0.3,
572
+ ci_color: str = "#2563eb",
573
+ ci_linewidth: float = 1.5,
574
+ breakdown_color: str = "#dc2626",
575
+ original_color: str = "#1f2937",
576
+ ax: Optional[Any] = None,
577
+ show: bool = True,
578
+ ) -> Any:
579
+ """
580
+ Plot sensitivity analysis results from Honest DiD.
581
+
582
+ Shows how treatment effect bounds and confidence intervals
583
+ change as the restriction parameter M varies.
584
+
585
+ Parameters
586
+ ----------
587
+ sensitivity_results : SensitivityResults
588
+ Results from HonestDiD.sensitivity_analysis().
589
+ show_bounds : bool, default=True
590
+ Whether to show the identified set bounds as shaded region.
591
+ show_ci : bool, default=True
592
+ Whether to show robust confidence interval lines.
593
+ breakdown_line : bool, default=True
594
+ Whether to show vertical line at breakdown value.
595
+ figsize : tuple, default=(10, 6)
596
+ Figure size (width, height) in inches.
597
+ title : str
598
+ Plot title.
599
+ xlabel : str
600
+ X-axis label.
601
+ ylabel : str
602
+ Y-axis label.
603
+ bounds_color : str
604
+ Color for identified set shading.
605
+ bounds_alpha : float
606
+ Transparency for identified set shading.
607
+ ci_color : str
608
+ Color for confidence interval lines.
609
+ ci_linewidth : float
610
+ Line width for CI lines.
611
+ breakdown_color : str
612
+ Color for breakdown value line.
613
+ original_color : str
614
+ Color for original estimate line.
615
+ ax : matplotlib.axes.Axes, optional
616
+ Axes to plot on. If None, creates new figure.
617
+ show : bool, default=True
618
+ Whether to call plt.show().
619
+
620
+ Returns
621
+ -------
622
+ matplotlib.axes.Axes
623
+ The axes object containing the plot.
624
+
625
+ Examples
626
+ --------
627
+ >>> from diff_diff import MultiPeriodDiD
628
+ >>> from diff_diff.honest_did import HonestDiD
629
+ >>> from diff_diff.visualization import plot_sensitivity
630
+ >>>
631
+ >>> # Fit event study and run sensitivity analysis
632
+ >>> results = MultiPeriodDiD().fit(data, ...)
633
+ >>> honest = HonestDiD(method='relative_magnitude')
634
+ >>> sensitivity = honest.sensitivity_analysis(results)
635
+ >>>
636
+ >>> # Create sensitivity plot
637
+ >>> plot_sensitivity(sensitivity)
638
+ """
639
+ try:
640
+ import matplotlib.pyplot as plt
641
+ except ImportError:
642
+ raise ImportError(
643
+ "matplotlib is required for plotting. " "Install it with: pip install matplotlib"
644
+ )
645
+
646
+ # Create figure if needed
647
+ if ax is None:
648
+ fig, ax = plt.subplots(figsize=figsize)
649
+ else:
650
+ fig = ax.get_figure()
651
+
652
+ M = sensitivity_results.M_values
653
+ bounds_arr = np.array(sensitivity_results.bounds)
654
+ ci_arr = np.array(sensitivity_results.robust_cis)
655
+
656
+ # Plot original estimate
657
+ ax.axhline(
658
+ y=sensitivity_results.original_estimate,
659
+ color=original_color,
660
+ linestyle="-",
661
+ linewidth=1.5,
662
+ label="Original estimate",
663
+ alpha=0.7,
664
+ )
665
+
666
+ # Plot zero line
667
+ ax.axhline(y=0, color="gray", linestyle="--", linewidth=1, alpha=0.5)
668
+
669
+ # Plot identified set bounds
670
+ if show_bounds:
671
+ ax.fill_between(
672
+ M,
673
+ bounds_arr[:, 0],
674
+ bounds_arr[:, 1],
675
+ alpha=bounds_alpha,
676
+ color=bounds_color,
677
+ label="Identified set",
678
+ )
679
+
680
+ # Plot confidence intervals
681
+ if show_ci:
682
+ ax.plot(M, ci_arr[:, 0], color=ci_color, linewidth=ci_linewidth, label="Robust CI")
683
+ ax.plot(M, ci_arr[:, 1], color=ci_color, linewidth=ci_linewidth)
684
+
685
+ # Plot breakdown line
686
+ if breakdown_line and sensitivity_results.breakdown_M is not None:
687
+ ax.axvline(
688
+ x=sensitivity_results.breakdown_M,
689
+ color=breakdown_color,
690
+ linestyle=":",
691
+ linewidth=2,
692
+ label=f"Breakdown (M={sensitivity_results.breakdown_M:.2f})",
693
+ )
694
+
695
+ ax.set_xlabel(xlabel)
696
+ ax.set_ylabel(ylabel)
697
+ ax.set_title(title)
698
+ ax.legend(loc="best")
699
+ ax.grid(True, alpha=0.3)
700
+
701
+ fig.tight_layout()
702
+
703
+ if show:
704
+ plt.show()
705
+
706
+ return ax
707
+
708
+
709
+ def plot_honest_event_study(
710
+ honest_results: "HonestDiDResults",
711
+ *,
712
+ periods: Optional[List[Any]] = None,
713
+ reference_period: Optional[Any] = None,
714
+ figsize: Tuple[float, float] = (10, 6),
715
+ title: str = "Event Study with Honest Confidence Intervals",
716
+ xlabel: str = "Period Relative to Treatment",
717
+ ylabel: str = "Treatment Effect",
718
+ original_color: str = "#6b7280",
719
+ honest_color: str = "#2563eb",
720
+ marker: str = "o",
721
+ markersize: int = 8,
722
+ capsize: int = 4,
723
+ ax: Optional[Any] = None,
724
+ show: bool = True,
725
+ ) -> Any:
726
+ """
727
+ Create event study plot with Honest DiD confidence intervals.
728
+
729
+ Shows both the original confidence intervals (assuming parallel trends)
730
+ and the robust confidence intervals that allow for bounded violations.
731
+
732
+ Parameters
733
+ ----------
734
+ honest_results : HonestDiDResults
735
+ Results from HonestDiD.fit() that include event_study_bounds.
736
+ periods : list, optional
737
+ Periods to plot. If None, uses all available periods.
738
+ reference_period : any, optional
739
+ Reference period to show as hollow marker.
740
+ figsize : tuple, default=(10, 6)
741
+ Figure size.
742
+ title : str
743
+ Plot title.
744
+ xlabel : str
745
+ X-axis label.
746
+ ylabel : str
747
+ Y-axis label.
748
+ original_color : str
749
+ Color for original (standard) confidence intervals.
750
+ honest_color : str
751
+ Color for honest (robust) confidence intervals.
752
+ marker : str
753
+ Marker style.
754
+ markersize : int
755
+ Marker size.
756
+ capsize : int
757
+ Error bar cap size.
758
+ ax : matplotlib.axes.Axes, optional
759
+ Axes to plot on.
760
+ show : bool, default=True
761
+ Whether to call plt.show().
762
+
763
+ Returns
764
+ -------
765
+ matplotlib.axes.Axes
766
+ The axes object.
767
+
768
+ Notes
769
+ -----
770
+ This function requires the HonestDiDResults to have been computed
771
+ with event_study_bounds. If only a scalar bound was computed,
772
+ use plot_sensitivity() instead.
773
+ """
774
+ try:
775
+ import matplotlib.pyplot as plt
776
+ except ImportError:
777
+ raise ImportError(
778
+ "matplotlib is required for plotting. " "Install it with: pip install matplotlib"
779
+ )
780
+
781
+ from scipy import stats as scipy_stats
782
+
783
+ # Get original results for standard CIs
784
+ original_results = honest_results.original_results
785
+ if original_results is None:
786
+ raise ValueError("HonestDiDResults must have original_results to plot event study")
787
+
788
+ # Extract data from original results
789
+ if hasattr(original_results, "period_effects"):
790
+ # MultiPeriodDiDResults
791
+ effects_dict = {p: pe.effect for p, pe in original_results.period_effects.items()}
792
+ se_dict = {p: pe.se for p, pe in original_results.period_effects.items()}
793
+ if periods is None:
794
+ periods = list(original_results.period_effects.keys())
795
+ elif hasattr(original_results, "event_study_effects"):
796
+ # CallawaySantAnnaResults
797
+ effects_dict = {
798
+ t: data["effect"] for t, data in original_results.event_study_effects.items()
799
+ }
800
+ se_dict = {t: data["se"] for t, data in original_results.event_study_effects.items()}
801
+ if periods is None:
802
+ periods = sorted(original_results.event_study_effects.keys())
803
+ else:
804
+ raise TypeError("Cannot extract event study data from original_results")
805
+
806
+ # Create figure
807
+ if ax is None:
808
+ fig, ax = plt.subplots(figsize=figsize)
809
+ else:
810
+ fig = ax.get_figure()
811
+
812
+ # Compute CIs
813
+ alpha = honest_results.alpha
814
+ z = scipy_stats.norm.ppf(1 - alpha / 2)
815
+
816
+ x_vals = list(range(len(periods)))
817
+
818
+ effects = [effects_dict[p] for p in periods]
819
+ original_ci_lower = [effects_dict[p] - z * se_dict[p] for p in periods]
820
+ original_ci_upper = [effects_dict[p] + z * se_dict[p] for p in periods]
821
+
822
+ # Get honest bounds if available for each period
823
+ if honest_results.event_study_bounds:
824
+ honest_ci_lower = [honest_results.event_study_bounds[p]["ci_lb"] for p in periods]
825
+ honest_ci_upper = [honest_results.event_study_bounds[p]["ci_ub"] for p in periods]
826
+ else:
827
+ # Use scalar bounds applied to all periods
828
+ honest_ci_lower = [honest_results.ci_lb] * len(periods)
829
+ honest_ci_upper = [honest_results.ci_ub] * len(periods)
830
+
831
+ # Zero line
832
+ ax.axhline(y=0, color="gray", linestyle="--", linewidth=1, alpha=0.5)
833
+
834
+ # Plot original CIs (thinner, background)
835
+ yerr_orig = [
836
+ [e - lower for e, lower in zip(effects, original_ci_lower)],
837
+ [u - e for e, u in zip(effects, original_ci_upper)],
838
+ ]
839
+ ax.errorbar(
840
+ x_vals,
841
+ effects,
842
+ yerr=yerr_orig,
843
+ fmt="none",
844
+ color=original_color,
845
+ capsize=capsize - 1,
846
+ linewidth=1,
847
+ alpha=0.6,
848
+ label="Standard CI",
849
+ )
850
+
851
+ # Plot honest CIs (thicker, foreground)
852
+ yerr_honest = [
853
+ [e - lower for e, lower in zip(effects, honest_ci_lower)],
854
+ [u - e for e, u in zip(effects, honest_ci_upper)],
855
+ ]
856
+ ax.errorbar(
857
+ x_vals,
858
+ effects,
859
+ yerr=yerr_honest,
860
+ fmt="none",
861
+ color=honest_color,
862
+ capsize=capsize,
863
+ linewidth=2,
864
+ label=f"Honest CI (M={honest_results.M:.2f})",
865
+ )
866
+
867
+ # Plot point estimates
868
+ for i, (x, effect, period) in enumerate(zip(x_vals, effects, periods)):
869
+ is_ref = period == reference_period
870
+ if is_ref:
871
+ ax.plot(
872
+ x,
873
+ effect,
874
+ marker=marker,
875
+ markersize=markersize,
876
+ markerfacecolor="white",
877
+ markeredgecolor=honest_color,
878
+ markeredgewidth=2,
879
+ zorder=3,
880
+ )
881
+ else:
882
+ ax.plot(x, effect, marker=marker, markersize=markersize, color=honest_color, zorder=3)
883
+
884
+ ax.set_xlabel(xlabel)
885
+ ax.set_ylabel(ylabel)
886
+ ax.set_title(title)
887
+ ax.set_xticks(x_vals)
888
+ ax.set_xticklabels([str(p) for p in periods])
889
+ ax.legend(loc="best")
890
+ ax.grid(True, alpha=0.3, axis="y")
891
+
892
+ fig.tight_layout()
893
+
894
+ if show:
895
+ plt.show()
896
+
897
+ return ax
898
+
899
+
900
+ def plot_bacon(
901
+ results: "BaconDecompositionResults",
902
+ *,
903
+ plot_type: str = "scatter",
904
+ figsize: Tuple[float, float] = (10, 6),
905
+ title: Optional[str] = None,
906
+ xlabel: str = "2x2 DiD Estimate",
907
+ ylabel: str = "Weight",
908
+ colors: Optional[Dict[str, str]] = None,
909
+ marker: str = "o",
910
+ markersize: int = 80,
911
+ alpha: float = 0.7,
912
+ show_weighted_avg: bool = True,
913
+ show_twfe_line: bool = True,
914
+ ax: Optional[Any] = None,
915
+ show: bool = True,
916
+ ) -> Any:
917
+ """
918
+ Visualize Goodman-Bacon decomposition results.
919
+
920
+ Creates either a scatter plot showing the weight and estimate for each
921
+ 2x2 comparison, or a stacked bar chart showing total weight by comparison
922
+ type.
923
+
924
+ Parameters
925
+ ----------
926
+ results : BaconDecompositionResults
927
+ Results from BaconDecomposition.fit() or bacon_decompose().
928
+ plot_type : str, default="scatter"
929
+ Type of plot to create:
930
+ - "scatter": Scatter plot with estimates on x-axis, weights on y-axis
931
+ - "bar": Stacked bar chart of weights by comparison type
932
+ figsize : tuple, default=(10, 6)
933
+ Figure size (width, height) in inches.
934
+ title : str, optional
935
+ Plot title. If None, uses a default based on plot_type.
936
+ xlabel : str, default="2x2 DiD Estimate"
937
+ X-axis label (scatter plot only).
938
+ ylabel : str, default="Weight"
939
+ Y-axis label.
940
+ colors : dict, optional
941
+ Dictionary mapping comparison types to colors. Keys are:
942
+ "treated_vs_never", "earlier_vs_later", "later_vs_earlier".
943
+ If None, uses default colors.
944
+ marker : str, default="o"
945
+ Marker style for scatter plot.
946
+ markersize : int, default=80
947
+ Marker size for scatter plot.
948
+ alpha : float, default=0.7
949
+ Transparency for markers/bars.
950
+ show_weighted_avg : bool, default=True
951
+ Whether to show weighted average lines for each comparison type
952
+ (scatter plot only).
953
+ show_twfe_line : bool, default=True
954
+ Whether to show a vertical line at the TWFE estimate (scatter plot only).
955
+ ax : matplotlib.axes.Axes, optional
956
+ Axes to plot on. If None, creates new figure.
957
+ show : bool, default=True
958
+ Whether to call plt.show() at the end.
959
+
960
+ Returns
961
+ -------
962
+ matplotlib.axes.Axes
963
+ The axes object containing the plot.
964
+
965
+ Examples
966
+ --------
967
+ Scatter plot (default):
968
+
969
+ >>> from diff_diff import bacon_decompose, plot_bacon
970
+ >>> results = bacon_decompose(data, outcome='y', unit='id',
971
+ ... time='t', first_treat='first_treat')
972
+ >>> plot_bacon(results)
973
+
974
+ Bar chart of weights by type:
975
+
976
+ >>> plot_bacon(results, plot_type='bar')
977
+
978
+ Customized scatter plot:
979
+
980
+ >>> plot_bacon(results,
981
+ ... colors={'treated_vs_never': 'green',
982
+ ... 'earlier_vs_later': 'blue',
983
+ ... 'later_vs_earlier': 'red'},
984
+ ... title='My Bacon Decomposition')
985
+
986
+ Notes
987
+ -----
988
+ The scatter plot is particularly useful for understanding:
989
+
990
+ 1. **Distribution of estimates**: Are 2x2 estimates clustered or spread?
991
+ Wide spread suggests heterogeneous treatment effects.
992
+
993
+ 2. **Weight concentration**: Do a few comparisons dominate the TWFE?
994
+ Points with high weights have more influence.
995
+
996
+ 3. **Forbidden comparison problem**: Red points (later_vs_earlier) show
997
+ comparisons using already-treated units as controls. If these have
998
+ different estimates than clean comparisons, TWFE may be biased.
999
+
1000
+ The bar chart provides a quick summary of how much weight falls on
1001
+ each comparison type, which is useful for assessing the severity
1002
+ of potential TWFE bias.
1003
+
1004
+ See Also
1005
+ --------
1006
+ bacon_decompose : Perform the decomposition
1007
+ BaconDecomposition : Class-based interface
1008
+ """
1009
+ try:
1010
+ import matplotlib.pyplot as plt
1011
+ except ImportError:
1012
+ raise ImportError(
1013
+ "matplotlib is required for plotting. " "Install it with: pip install matplotlib"
1014
+ )
1015
+
1016
+ # Default colors
1017
+ if colors is None:
1018
+ colors = {
1019
+ "treated_vs_never": "#22c55e", # Green - clean comparison
1020
+ "earlier_vs_later": "#3b82f6", # Blue - valid comparison
1021
+ "later_vs_earlier": "#ef4444", # Red - forbidden comparison
1022
+ }
1023
+
1024
+ # Default titles
1025
+ if title is None:
1026
+ if plot_type == "scatter":
1027
+ title = "Goodman-Bacon Decomposition"
1028
+ else:
1029
+ title = "TWFE Weight by Comparison Type"
1030
+
1031
+ # Create figure if needed
1032
+ if ax is None:
1033
+ fig, ax = plt.subplots(figsize=figsize)
1034
+ else:
1035
+ fig = ax.get_figure()
1036
+
1037
+ if plot_type == "scatter":
1038
+ _plot_bacon_scatter(
1039
+ ax,
1040
+ results,
1041
+ colors,
1042
+ marker,
1043
+ markersize,
1044
+ alpha,
1045
+ show_weighted_avg,
1046
+ show_twfe_line,
1047
+ xlabel,
1048
+ ylabel,
1049
+ title,
1050
+ )
1051
+ elif plot_type == "bar":
1052
+ _plot_bacon_bar(ax, results, colors, alpha, ylabel, title)
1053
+ else:
1054
+ raise ValueError(f"Unknown plot_type: {plot_type}. Use 'scatter' or 'bar'.")
1055
+
1056
+ fig.tight_layout()
1057
+
1058
+ if show:
1059
+ plt.show()
1060
+
1061
+ return ax
1062
+
1063
+
1064
+ def _plot_bacon_scatter(
1065
+ ax: Any,
1066
+ results: "BaconDecompositionResults",
1067
+ colors: Dict[str, str],
1068
+ marker: str,
1069
+ markersize: int,
1070
+ alpha: float,
1071
+ show_weighted_avg: bool,
1072
+ show_twfe_line: bool,
1073
+ xlabel: str,
1074
+ ylabel: str,
1075
+ title: str,
1076
+ ) -> None:
1077
+ """Create scatter plot of Bacon decomposition."""
1078
+ # Separate comparisons by type
1079
+ by_type: Dict[str, List[Tuple[float, float]]] = {
1080
+ "treated_vs_never": [],
1081
+ "earlier_vs_later": [],
1082
+ "later_vs_earlier": [],
1083
+ }
1084
+
1085
+ for comp in results.comparisons:
1086
+ by_type[comp.comparison_type].append((comp.estimate, comp.weight))
1087
+
1088
+ # Plot each type
1089
+ labels = {
1090
+ "treated_vs_never": "Treated vs Never-treated",
1091
+ "earlier_vs_later": "Earlier vs Later treated",
1092
+ "later_vs_earlier": "Later vs Earlier (forbidden)",
1093
+ }
1094
+
1095
+ for ctype, points in by_type.items():
1096
+ if not points:
1097
+ continue
1098
+ estimates = [p[0] for p in points]
1099
+ weights = [p[1] for p in points]
1100
+ ax.scatter(
1101
+ estimates,
1102
+ weights,
1103
+ c=colors[ctype],
1104
+ label=labels[ctype],
1105
+ marker=marker,
1106
+ s=markersize,
1107
+ alpha=alpha,
1108
+ edgecolors="white",
1109
+ linewidths=0.5,
1110
+ )
1111
+
1112
+ # Show weighted average lines
1113
+ if show_weighted_avg:
1114
+ effect_by_type = results.effect_by_type()
1115
+ for ctype, avg_effect in effect_by_type.items():
1116
+ if avg_effect is not None and by_type[ctype]:
1117
+ ax.axvline(
1118
+ x=avg_effect,
1119
+ color=colors[ctype],
1120
+ linestyle="--",
1121
+ alpha=0.5,
1122
+ linewidth=1.5,
1123
+ )
1124
+
1125
+ # Show TWFE estimate line
1126
+ if show_twfe_line:
1127
+ ax.axvline(
1128
+ x=results.twfe_estimate,
1129
+ color="black",
1130
+ linestyle="-",
1131
+ linewidth=2,
1132
+ label=f"TWFE = {results.twfe_estimate:.4f}",
1133
+ )
1134
+
1135
+ ax.set_xlabel(xlabel)
1136
+ ax.set_ylabel(ylabel)
1137
+ ax.set_title(title)
1138
+ ax.legend(loc="best")
1139
+ ax.grid(True, alpha=0.3)
1140
+
1141
+ # Add zero line
1142
+ ax.axvline(x=0, color="gray", linestyle=":", alpha=0.5)
1143
+
1144
+
1145
+ def _plot_bacon_bar(
1146
+ ax: Any,
1147
+ results: "BaconDecompositionResults",
1148
+ colors: Dict[str, str],
1149
+ alpha: float,
1150
+ ylabel: str,
1151
+ title: str,
1152
+ ) -> None:
1153
+ """Create stacked bar chart of weights by comparison type."""
1154
+ # Get weights
1155
+ weights = results.weight_by_type()
1156
+
1157
+ # Labels and colors
1158
+ type_order = ["treated_vs_never", "earlier_vs_later", "later_vs_earlier"]
1159
+ labels = {
1160
+ "treated_vs_never": "Treated vs Never-treated",
1161
+ "earlier_vs_later": "Earlier vs Later",
1162
+ "later_vs_earlier": "Later vs Earlier\n(forbidden)",
1163
+ }
1164
+
1165
+ # Create bar data
1166
+ bar_labels = [labels[t] for t in type_order]
1167
+ bar_weights = [weights[t] for t in type_order]
1168
+ bar_colors = [colors[t] for t in type_order]
1169
+
1170
+ # Create bars
1171
+ bars = ax.bar(
1172
+ bar_labels,
1173
+ bar_weights,
1174
+ color=bar_colors,
1175
+ alpha=alpha,
1176
+ edgecolor="white",
1177
+ linewidth=1,
1178
+ )
1179
+
1180
+ # Add percentage labels on bars
1181
+ for bar, weight in zip(bars, bar_weights):
1182
+ if weight > 0.01: # Only label if > 1%
1183
+ height = bar.get_height()
1184
+ ax.annotate(
1185
+ f"{weight:.1%}",
1186
+ xy=(bar.get_x() + bar.get_width() / 2, height),
1187
+ xytext=(0, 3),
1188
+ textcoords="offset points",
1189
+ ha="center",
1190
+ va="bottom",
1191
+ fontsize=10,
1192
+ fontweight="bold",
1193
+ )
1194
+
1195
+ # Add weighted average effect annotations
1196
+ effects = results.effect_by_type()
1197
+ for bar, ctype in zip(bars, type_order):
1198
+ effect = effects[ctype]
1199
+ if effect is not None and weights[ctype] > 0.01:
1200
+ ax.annotate(
1201
+ f"β = {effect:.3f}",
1202
+ xy=(bar.get_x() + bar.get_width() / 2, bar.get_height() / 2),
1203
+ ha="center",
1204
+ va="center",
1205
+ fontsize=9,
1206
+ color="white",
1207
+ fontweight="bold",
1208
+ )
1209
+
1210
+ ax.set_ylabel(ylabel)
1211
+ ax.set_title(title)
1212
+ ax.set_ylim(0, 1.1)
1213
+
1214
+ # Add horizontal line at total weight = 1
1215
+ ax.axhline(y=1.0, color="gray", linestyle="--", alpha=0.5)
1216
+
1217
+ # Add TWFE estimate as text
1218
+ ax.text(
1219
+ 0.98,
1220
+ 0.98,
1221
+ f"TWFE = {results.twfe_estimate:.4f}",
1222
+ transform=ax.transAxes,
1223
+ ha="right",
1224
+ va="top",
1225
+ fontsize=10,
1226
+ bbox=dict(boxstyle="round", facecolor="white", alpha=0.8),
1227
+ )
1228
+
1229
+
1230
+ def plot_power_curve(
1231
+ results: Optional[Union["PowerResults", "SimulationPowerResults", pd.DataFrame]] = None,
1232
+ *,
1233
+ effect_sizes: Optional[List[float]] = None,
1234
+ powers: Optional[List[float]] = None,
1235
+ mde: Optional[float] = None,
1236
+ target_power: float = 0.80,
1237
+ plot_type: str = "effect",
1238
+ figsize: Tuple[float, float] = (10, 6),
1239
+ title: Optional[str] = None,
1240
+ xlabel: Optional[str] = None,
1241
+ ylabel: str = "Power",
1242
+ color: str = "#2563eb",
1243
+ mde_color: str = "#dc2626",
1244
+ target_color: str = "#22c55e",
1245
+ linewidth: float = 2.0,
1246
+ show_mde_line: bool = True,
1247
+ show_target_line: bool = True,
1248
+ show_grid: bool = True,
1249
+ ax: Optional[Any] = None,
1250
+ show: bool = True,
1251
+ ) -> Any:
1252
+ """
1253
+ Create a power curve visualization.
1254
+
1255
+ Shows how statistical power changes with effect size or sample size,
1256
+ helping researchers understand the trade-offs in study design.
1257
+
1258
+ Parameters
1259
+ ----------
1260
+ results : PowerResults, SimulationPowerResults, or DataFrame, optional
1261
+ Results object from PowerAnalysis or simulate_power(), or a DataFrame
1262
+ with columns 'effect_size' and 'power' (or 'sample_size' and 'power').
1263
+ If None, must provide effect_sizes and powers directly.
1264
+ effect_sizes : list of float, optional
1265
+ Effect sizes (x-axis values). Required if results is None.
1266
+ powers : list of float, optional
1267
+ Power values (y-axis values). Required if results is None.
1268
+ mde : float, optional
1269
+ Minimum detectable effect to mark on the plot.
1270
+ target_power : float, default=0.80
1271
+ Target power level to show as horizontal line.
1272
+ plot_type : str, default="effect"
1273
+ Type of power curve: "effect" (power vs effect size) or
1274
+ "sample" (power vs sample size).
1275
+ figsize : tuple, default=(10, 6)
1276
+ Figure size (width, height) in inches.
1277
+ title : str, optional
1278
+ Plot title. If None, uses a sensible default.
1279
+ xlabel : str, optional
1280
+ X-axis label. If None, uses a sensible default.
1281
+ ylabel : str, default="Power"
1282
+ Y-axis label.
1283
+ color : str, default="#2563eb"
1284
+ Color for the power curve line.
1285
+ mde_color : str, default="#dc2626"
1286
+ Color for the MDE vertical line.
1287
+ target_color : str, default="#22c55e"
1288
+ Color for the target power horizontal line.
1289
+ linewidth : float, default=2.0
1290
+ Line width for the power curve.
1291
+ show_mde_line : bool, default=True
1292
+ Whether to show vertical line at MDE.
1293
+ show_target_line : bool, default=True
1294
+ Whether to show horizontal line at target power.
1295
+ show_grid : bool, default=True
1296
+ Whether to show grid lines.
1297
+ ax : matplotlib.axes.Axes, optional
1298
+ Axes to plot on. If None, creates new figure.
1299
+ show : bool, default=True
1300
+ Whether to call plt.show() at the end.
1301
+
1302
+ Returns
1303
+ -------
1304
+ matplotlib.axes.Axes
1305
+ The axes object containing the plot.
1306
+
1307
+ Examples
1308
+ --------
1309
+ From PowerAnalysis results:
1310
+
1311
+ >>> from diff_diff import PowerAnalysis, plot_power_curve
1312
+ >>> pa = PowerAnalysis(power=0.80)
1313
+ >>> curve_df = pa.power_curve(n_treated=50, n_control=50, sigma=5.0)
1314
+ >>> mde_result = pa.mde(n_treated=50, n_control=50, sigma=5.0)
1315
+ >>> plot_power_curve(curve_df, mde=mde_result.mde)
1316
+
1317
+ From simulation results:
1318
+
1319
+ >>> from diff_diff import simulate_power, DifferenceInDifferences
1320
+ >>> results = simulate_power(
1321
+ ... DifferenceInDifferences(),
1322
+ ... effect_sizes=[1, 2, 3, 5, 7, 10],
1323
+ ... n_simulations=200
1324
+ ... )
1325
+ >>> plot_power_curve(results)
1326
+
1327
+ Manual data:
1328
+
1329
+ >>> plot_power_curve(
1330
+ ... effect_sizes=[1, 2, 3, 4, 5],
1331
+ ... powers=[0.2, 0.5, 0.75, 0.90, 0.97],
1332
+ ... mde=2.5,
1333
+ ... target_power=0.80
1334
+ ... )
1335
+ """
1336
+ try:
1337
+ import matplotlib.pyplot as plt
1338
+ except ImportError:
1339
+ raise ImportError(
1340
+ "matplotlib is required for plotting. " "Install it with: pip install matplotlib"
1341
+ )
1342
+
1343
+ # Extract data from results if provided
1344
+ if results is not None:
1345
+ if isinstance(results, pd.DataFrame):
1346
+ # DataFrame input
1347
+ if "effect_size" in results.columns:
1348
+ effect_sizes = results["effect_size"].tolist()
1349
+ plot_type = "effect"
1350
+ elif "sample_size" in results.columns:
1351
+ effect_sizes = results["sample_size"].tolist()
1352
+ plot_type = "sample"
1353
+ else:
1354
+ raise ValueError("DataFrame must have 'effect_size' or 'sample_size' column")
1355
+ powers = results["power"].tolist()
1356
+ elif hasattr(results, "effect_sizes") and hasattr(results, "powers"):
1357
+ # SimulationPowerResults
1358
+ effect_sizes = results.effect_sizes
1359
+ powers = results.powers
1360
+ if mde is None and hasattr(results, "true_effect"):
1361
+ # Mark true effect on plot
1362
+ mde = results.true_effect
1363
+ elif hasattr(results, "mde"):
1364
+ # PowerResults - create curve data
1365
+ raise ValueError(
1366
+ "PowerResults should be used to get mde value, not as direct input. "
1367
+ "Use PowerAnalysis.power_curve() to generate curve data."
1368
+ )
1369
+ else:
1370
+ raise TypeError(f"Cannot extract power curve data from {type(results).__name__}")
1371
+ elif effect_sizes is None or powers is None:
1372
+ raise ValueError("Must provide either 'results' or both 'effect_sizes' and 'powers'")
1373
+
1374
+ # Default titles and labels
1375
+ if title is None:
1376
+ if plot_type == "effect":
1377
+ title = "Power Curve"
1378
+ else:
1379
+ title = "Power vs Sample Size"
1380
+
1381
+ if xlabel is None:
1382
+ if plot_type == "effect":
1383
+ xlabel = "Effect Size"
1384
+ else:
1385
+ xlabel = "Sample Size"
1386
+
1387
+ # Create figure if needed
1388
+ if ax is None:
1389
+ fig, ax = plt.subplots(figsize=figsize)
1390
+ else:
1391
+ fig = ax.get_figure()
1392
+
1393
+ # Plot power curve
1394
+ ax.plot(effect_sizes, powers, color=color, linewidth=linewidth, label="Power")
1395
+
1396
+ # Add target power line
1397
+ if show_target_line:
1398
+ ax.axhline(
1399
+ y=target_power,
1400
+ color=target_color,
1401
+ linestyle="--",
1402
+ linewidth=1.5,
1403
+ alpha=0.7,
1404
+ label=f"Target power ({target_power:.0%})",
1405
+ )
1406
+
1407
+ # Add MDE line
1408
+ if show_mde_line and mde is not None:
1409
+ ax.axvline(
1410
+ x=mde,
1411
+ color=mde_color,
1412
+ linestyle=":",
1413
+ linewidth=1.5,
1414
+ alpha=0.7,
1415
+ label=f"MDE = {mde:.3f}",
1416
+ )
1417
+
1418
+ # Mark intersection point
1419
+ # Find power at MDE
1420
+ if mde in effect_sizes:
1421
+ idx = effect_sizes.index(mde)
1422
+ power_at_mde = powers[idx]
1423
+ else:
1424
+ # Interpolate
1425
+ effect_arr = np.array(effect_sizes)
1426
+ power_arr = np.array(powers)
1427
+ if effect_arr.min() <= mde <= effect_arr.max():
1428
+ power_at_mde = np.interp(mde, effect_arr, power_arr)
1429
+ else:
1430
+ power_at_mde = None
1431
+
1432
+ if power_at_mde is not None:
1433
+ ax.scatter([mde], [power_at_mde], color=mde_color, s=50, zorder=5)
1434
+
1435
+ # Configure axes
1436
+ ax.set_xlabel(xlabel)
1437
+ ax.set_ylabel(ylabel)
1438
+ ax.set_title(title)
1439
+
1440
+ # Y-axis from 0 to 1
1441
+ ax.set_ylim(0, 1.05)
1442
+
1443
+ # Format y-axis as percentage
1444
+ ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda y, _: f"{y:.0%}"))
1445
+
1446
+ if show_grid:
1447
+ ax.grid(True, alpha=0.3)
1448
+
1449
+ ax.legend(loc="lower right")
1450
+
1451
+ fig.tight_layout()
1452
+
1453
+ if show:
1454
+ plt.show()
1455
+
1456
+ return ax
1457
+
1458
+
1459
+ def plot_pretrends_power(
1460
+ results: Optional[Union["PreTrendsPowerResults", "PreTrendsPowerCurve", pd.DataFrame]] = None,
1461
+ *,
1462
+ M_values: Optional[List[float]] = None,
1463
+ powers: Optional[List[float]] = None,
1464
+ mdv: Optional[float] = None,
1465
+ target_power: float = 0.80,
1466
+ figsize: Tuple[float, float] = (10, 6),
1467
+ title: str = "Pre-Trends Test Power Curve",
1468
+ xlabel: str = "Violation Magnitude (M)",
1469
+ ylabel: str = "Power",
1470
+ color: str = "#2563eb",
1471
+ mdv_color: str = "#dc2626",
1472
+ target_color: str = "#22c55e",
1473
+ linewidth: float = 2.0,
1474
+ show_mdv_line: bool = True,
1475
+ show_target_line: bool = True,
1476
+ show_grid: bool = True,
1477
+ ax: Optional[Any] = None,
1478
+ show: bool = True,
1479
+ ) -> Any:
1480
+ """
1481
+ Plot pre-trends test power curve.
1482
+
1483
+ Visualizes how the power to detect parallel trends violations changes
1484
+ with the violation magnitude (M). This helps understand what violations
1485
+ your pre-trends test is capable of detecting.
1486
+
1487
+ Parameters
1488
+ ----------
1489
+ results : PreTrendsPowerResults, PreTrendsPowerCurve, or DataFrame, optional
1490
+ Results from PreTrendsPower.fit() or power_curve(), or a DataFrame
1491
+ with columns 'M' and 'power'. If None, must provide M_values and powers.
1492
+ M_values : list of float, optional
1493
+ Violation magnitudes (x-axis). Required if results is None.
1494
+ powers : list of float, optional
1495
+ Power values (y-axis). Required if results is None.
1496
+ mdv : float, optional
1497
+ Minimum detectable violation to mark on the plot.
1498
+ target_power : float, default=0.80
1499
+ Target power level to show as horizontal line.
1500
+ figsize : tuple, default=(10, 6)
1501
+ Figure size (width, height) in inches.
1502
+ title : str
1503
+ Plot title.
1504
+ xlabel : str
1505
+ X-axis label.
1506
+ ylabel : str
1507
+ Y-axis label.
1508
+ color : str, default="#2563eb"
1509
+ Color for the power curve line.
1510
+ mdv_color : str, default="#dc2626"
1511
+ Color for the MDV vertical line.
1512
+ target_color : str, default="#22c55e"
1513
+ Color for the target power horizontal line.
1514
+ linewidth : float, default=2.0
1515
+ Line width for the power curve.
1516
+ show_mdv_line : bool, default=True
1517
+ Whether to show vertical line at MDV.
1518
+ show_target_line : bool, default=True
1519
+ Whether to show horizontal line at target power.
1520
+ show_grid : bool, default=True
1521
+ Whether to show grid lines.
1522
+ ax : matplotlib.axes.Axes, optional
1523
+ Axes to plot on. If None, creates new figure.
1524
+ show : bool, default=True
1525
+ Whether to call plt.show() at the end.
1526
+
1527
+ Returns
1528
+ -------
1529
+ matplotlib.axes.Axes
1530
+ The axes object containing the plot.
1531
+
1532
+ Examples
1533
+ --------
1534
+ From PreTrendsPower results:
1535
+
1536
+ >>> from diff_diff import MultiPeriodDiD
1537
+ >>> from diff_diff.pretrends import PreTrendsPower
1538
+ >>> from diff_diff.visualization import plot_pretrends_power
1539
+ >>>
1540
+ >>> mp_did = MultiPeriodDiD()
1541
+ >>> event_results = mp_did.fit(data, outcome='y', treatment='treated',
1542
+ ... time='period', post_periods=[4, 5, 6, 7])
1543
+ >>>
1544
+ >>> pt = PreTrendsPower()
1545
+ >>> curve = pt.power_curve(event_results)
1546
+ >>> plot_pretrends_power(curve)
1547
+
1548
+ From manual data:
1549
+
1550
+ >>> plot_pretrends_power(
1551
+ ... M_values=[0, 0.5, 1, 1.5, 2],
1552
+ ... powers=[0.05, 0.3, 0.6, 0.85, 0.95],
1553
+ ... mdv=1.2,
1554
+ ... target_power=0.80
1555
+ ... )
1556
+
1557
+ Notes
1558
+ -----
1559
+ The power curve shows how likely you are to reject the null hypothesis
1560
+ of parallel trends given a true violation of magnitude M. Key points:
1561
+
1562
+ 1. **At M=0**: Power equals alpha (size of the test).
1563
+ 2. **At MDV**: Power equals target power (default 80%).
1564
+ 3. **Beyond MDV**: Power increases toward 100%.
1565
+
1566
+ A steep power curve indicates a sensitive pre-trends test. A flat curve
1567
+ indicates the test has limited ability to detect violations, suggesting
1568
+ you should use HonestDiD sensitivity analysis for robust inference.
1569
+
1570
+ See Also
1571
+ --------
1572
+ PreTrendsPower : Main class for pre-trends power analysis
1573
+ plot_sensitivity : Plot HonestDiD sensitivity analysis
1574
+ """
1575
+ try:
1576
+ import matplotlib.pyplot as plt
1577
+ except ImportError:
1578
+ raise ImportError(
1579
+ "matplotlib is required for plotting. " "Install it with: pip install matplotlib"
1580
+ )
1581
+
1582
+ # Extract data from results if provided
1583
+ if results is not None:
1584
+ if isinstance(results, pd.DataFrame):
1585
+ if "M" not in results.columns or "power" not in results.columns:
1586
+ raise ValueError("DataFrame must have 'M' and 'power' columns")
1587
+ M_values = results["M"].tolist()
1588
+ powers = results["power"].tolist()
1589
+ elif hasattr(results, "M_values") and hasattr(results, "powers"):
1590
+ # PreTrendsPowerCurve
1591
+ M_values = results.M_values.tolist()
1592
+ powers = results.powers.tolist()
1593
+ if mdv is None:
1594
+ mdv = results.mdv
1595
+ if target_power is None:
1596
+ target_power = results.target_power
1597
+ elif hasattr(results, "mdv") and hasattr(results, "power"):
1598
+ # Single PreTrendsPowerResults - create a simple plot
1599
+ if mdv is None:
1600
+ mdv = results.mdv
1601
+ # Create minimal curve around MDV
1602
+ if np.isfinite(mdv):
1603
+ M_values = [0, mdv * 0.5, mdv, mdv * 1.5, mdv * 2]
1604
+ else:
1605
+ M_values = [0, 1, 2, 3, 4]
1606
+ # We don't have the actual powers, so we need to create a placeholder
1607
+ # Just show MDV marker
1608
+ powers = None
1609
+ else:
1610
+ raise TypeError(f"Cannot extract power curve data from {type(results).__name__}")
1611
+ elif M_values is None or powers is None:
1612
+ raise ValueError("Must provide either 'results' or both 'M_values' and 'powers'")
1613
+
1614
+ # Create figure if needed
1615
+ if ax is None:
1616
+ fig, ax = plt.subplots(figsize=figsize)
1617
+ else:
1618
+ fig = ax.get_figure()
1619
+
1620
+ # Plot power curve if we have powers
1621
+ if powers is not None:
1622
+ ax.plot(M_values, powers, color=color, linewidth=linewidth, label="Power")
1623
+
1624
+ # Add target power line
1625
+ if show_target_line:
1626
+ ax.axhline(
1627
+ y=target_power,
1628
+ color=target_color,
1629
+ linestyle="--",
1630
+ linewidth=1.5,
1631
+ alpha=0.7,
1632
+ label=f"Target power ({target_power:.0%})",
1633
+ )
1634
+
1635
+ # Add MDV line
1636
+ if show_mdv_line and mdv is not None and np.isfinite(mdv):
1637
+ ax.axvline(
1638
+ x=mdv,
1639
+ color=mdv_color,
1640
+ linestyle=":",
1641
+ linewidth=1.5,
1642
+ alpha=0.7,
1643
+ label=f"MDV = {mdv:.3f}",
1644
+ )
1645
+
1646
+ # Mark intersection point if we have powers
1647
+ if powers is not None:
1648
+ # Find power at MDV (interpolate)
1649
+ M_arr = np.array(M_values)
1650
+ power_arr = np.array(powers)
1651
+ if M_arr.min() <= mdv <= M_arr.max():
1652
+ power_at_mdv = np.interp(mdv, M_arr, power_arr)
1653
+ ax.scatter([mdv], [power_at_mdv], color=mdv_color, s=50, zorder=5)
1654
+
1655
+ # Configure axes
1656
+ ax.set_xlabel(xlabel)
1657
+ ax.set_ylabel(ylabel)
1658
+ ax.set_title(title)
1659
+
1660
+ # Y-axis from 0 to 1
1661
+ ax.set_ylim(0, 1.05)
1662
+
1663
+ # Format y-axis as percentage
1664
+ ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda y, _: f"{y:.0%}"))
1665
+
1666
+ if show_grid:
1667
+ ax.grid(True, alpha=0.3)
1668
+
1669
+ ax.legend(loc="lower right")
1670
+
1671
+ fig.tight_layout()
1672
+
1673
+ if show:
1674
+ plt.show()
1675
+
1676
+ return ax