Coverage for src/courtpy/artist/plots.py: 95%

313 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-22 15:51 +0000

1"""Techniques that draw figures of cases, courts, panels, and judges. 

2 

3Each is an `amos` plot (`amos.plots.Plot`), so it is added to the `amos` 

4library when courtpy is imported, can be named in the settings of an 

5"artist" worker, takes the parameters that every plot takes ("width", 

6"height", "title", "style", and so on), and adds its figure to the 

7dataset's `figures` under its name. Courts are labeled with their 

8"feature_name" in the jurisdiction's table of courts (such as "Tenth 

9Circuit"; see `courtpy.courts.court_labels`), in the order of the table. 

10 

11A rate is the share of the cases that have a flag (or the mean of a 

12number), measured from the cases themselves, so it is drawn without a 

13confidence interval. Each bar says how many cases it counts. 

14 

15| Technique | Draws | Needs | 

16| --- | --- | --- | 

17| `court_rates` | The rate of a column in each court, with the rate of every court as a line. | `Cases`, with the column (the label, unless "column" is set). | 

18| `cases_over_time` | The number of cases of each court in each year, a panel for each court. | `Cases`, with "year". | 

19| `issues_over_time` | The number of cases with each issue (a column of flags, such as "criminal_firearm") in each court in each year, a panel for each court. | `Cases`, with "year" and the columns in "issues". | 

20| `panel_composition` | The rate of a column for each composition of the panel by the parties of the presidents who appointed its judges ("DDD" to "RRR"), split by another column if "by" is set. | `Cases`, with the judges' parties (from `add_biography` or `code_panels`). | 

21| `lower_court_rates` | The rate of a column for each court whose decisions a court reviews, a panel for each reviewing court. | `Cases`, with "lower_court_name" or "lower_court_num". | 

22| `trends_by_administration` | The yearly rate of a column in each court, a panel for each court, with the terms of Democratic and Republican presidents shaded. | `Cases`, with "year". | 

23| `idb_confusion_matrices` | A confusion matrix for each variable that the data and the Integrated Database both have, with Cohen's kappa. | The table of `compare_with_idb`. | 

24| `idb_missing_differences` | The share of each variable among the appeals of the Integrated Database that the data has minus the share among those it lacks, for each circuit or district. | The second table of `compare_with_idb`. | 

25| `judge_network` | The judges as a network, joined by how often they sat together (or, with "dissents", how often one dissented from the other), colored by party. | `Votes` (see `cases_to_votes`). | 

26 

27Contents: 

28 CasesOverTime: the number of cases of each court in each year. 

29 CourtRates: the rate of a column in each court. 

30 IdbConfusionMatrices: how the data agrees with the Integrated Database, 

31 a confusion matrix for each variable. 

32 IdbMissingDifferences: how the Integrated Database's appeals that the 

33 data lacks differ from those it has, in each group. 

34 IssuesOverTime: the number of cases with each issue in each court in 

35 each year. 

36 JudgeNetwork: the judges as a network of who sat with, or dissented 

37 from, whom. 

38 LowerCourtRates: the rate of a column for each court below, by the 

39 court that reviewed it. 

40 PanelComposition: the rate of a column for each composition of the 

41 panel by party. 

42 TrendsByAdministration: the yearly rate of a column in each court, with 

43 the presidents' terms shaded. 

44 _DEFAULT_RATE: the column whose rate is drawn when there is no label and 

45 none is named. 

46 _PARTY_COLORS: the colors of Democratic and Republican appointees and 

47 presidents. 

48 

49""" 

50 

51from __future__ import annotations 

52 

53import dataclasses 

54import itertools 

55import math 

56from collections.abc import Sequence 

57from typing import Any, ClassVar, Literal 

58 

59import amos 

60import numpy as np 

61import pandas as pd 

62 

63from ..core import cases, utilities 

64from ..references import courts, judges, politics 

65 

66# The column whose rate is drawn when the dataset has no label and none is 

67# named: whether the court of appeals reversed the court below. 

68_DEFAULT_RATE: str = 'outcome_reversal' 

69# The colors of Democratic (-1) and Republican (1) appointees and 

70# presidents, as the parties are usually drawn. 

71_PARTY_COLORS: dict[int, str] = {-1: '#1f5aa6', 1: '#c0392b'} 

72 

73 

74@dataclasses.dataclass 

75class CourtRates(amos.plots.Plot): 

76 """Plots the rate of a column in each court, as bars. 

77 

78 Each bar is the share of the court's cases that have a flag (or the mean 

79 of a number), with the number of cases it counts. A dashed line is the 

80 rate of all the cases together. 

81 

82 """ 

83 

84 starts_at_zero: ClassVar[str] = 'x' 

85 

86 """ Required Methods """ 

87 

88 def draw( 

89 self, 

90 item: amos.Dataset, 

91 figure: Any, 

92 *, 

93 column: str | None = None, 

94 court_name: str = 'court_name', 

95 court_num: str = 'court_num', 

96 jurisdiction: str = 'federal', 

97 **kwargs: Any) -> None: 

98 """Draws the rate of `column` in each court. 

99 

100 Args: 

101 item: the cases. 

102 figure: the figure to draw on. 

103 column: the column whose rate is drawn. Defaults to `None`, which 

104 uses the dataset's label, or else `_DEFAULT_RATE`. 

105 court_name: the column with courtpy's name for each case's court. 

106 Defaults to "court_name". 

107 court_num: the column with courtpy's number for each case's 

108 court. Defaults to "court_num". 

109 jurisdiction: the folder of the jurisdiction's table of courts. 

110 Defaults to "federal". 

111 **kwargs: not used. 

112 

113 """ 

114 data = item.data 

115 column = _rate_column(item, column) 

116 table = pd.DataFrame({ 

117 'court': courts.court_labels( 

118 data, court_name = court_name, court_num = court_num, 

119 jurisdiction = jurisdiction), 

120 'value': _numbers(data[column])}).dropna() 

121 rates = table.groupby('court', observed = True)['value'].agg( 

122 ['mean', 'size']) 

123 shares = _is_share(table['value']) 

124 axes = figure.subplots() 

125 places = np.arange(len(rates)) 

126 axes.barh(places, rates['mean']) 

127 axes.set_yticks(places, [str(c) for c in rates.index]) 

128 axes.invert_yaxis() 

129 for place, (rate, count) in zip( 

130 places, rates.itertuples(index = False), strict = True): 

131 axes.annotate( 

132 f' {_amount(rate, shares)} (n = {count:,})', (rate, place), 

133 va = 'center', fontsize = 'small') 

134 overall = table['value'].mean() 

135 axes.axvline( 

136 overall, color = '0.35', linestyle = '--', 

137 label = f'All courts: {_amount(overall, shares)}') 

138 # Room to the right of the longest bar for its label. 

139 axes.set_xlim(0, max(rates['mean'].max(), overall) * 1.45 or 1) 

140 figure.legend(loc = 'outside lower center') 

141 axes.set_xlabel(_rate_name(column, shares)) 

142 _as_percent(axes.xaxis, shares) 

143 

144 

145@dataclasses.dataclass 

146class CasesOverTime(amos.plots.Plot): 

147 """Plots the number of cases of each court in each year. 

148 

149 Each court in the data has a panel, labeled with its name, and the 

150 panels share their axes so that the courts can be compared. 

151 

152 """ 

153 

154 size: ClassVar[tuple[float, float]] = (9.6, 7.2) 

155 shared_axes: ClassVar[str] = 'xy' 

156 starts_at_zero: ClassVar[str] = 'y' 

157 

158 """ Required Methods """ 

159 

160 def draw( 

161 self, 

162 item: amos.Dataset, 

163 figure: Any, 

164 *, 

165 year: str = 'year', 

166 court_name: str = 'court_name', 

167 court_num: str = 'court_num', 

168 jurisdiction: str = 'federal', 

169 columns: int = 4, 

170 **kwargs: Any) -> None: 

171 """Draws the number of cases of each court in each year. 

172 

173 Args: 

174 item: the cases. 

175 figure: the figure to draw on. 

176 year: the column with each case's year. Defaults to "year". 

177 court_name: the column with courtpy's name for each case's court. 

178 Defaults to "court_name". 

179 court_num: the column with courtpy's number for each case's 

180 court. Defaults to "court_num". 

181 jurisdiction: the folder of the jurisdiction's table of courts. 

182 Defaults to "federal". 

183 columns: the most panels in a row. Defaults to 4. 

184 **kwargs: not used. 

185 

186 """ 

187 data = item.data 

188 counts = _yearly( 

189 data, pd.Series(1, index = data.index, name = 'cases'), 

190 year = year, court_name = court_name, court_num = court_num, 

191 jurisdiction = jurisdiction, how = 'sum') 

192 panels = _court_panels(figure, counts.index, columns) 

193 years = counts.columns.to_numpy() 

194 for court, axes in panels.items(): 

195 axes.plot(years, counts.loc[court].to_numpy(), marker = '.') 

196 figure.supxlabel('Year') 

197 figure.supylabel('Cases') 

198 

199 

200@dataclasses.dataclass 

201class IssuesOverTime(amos.plots.Plot): 

202 """Plots the number of cases with each issue in each court in each year. 

203 

204 An issue is a column of flags, such as "criminal_firearm" (from the 

205 rules) or "type_immigration" (from `code_case_type`). Each court in the 

206 data has a panel, labeled with its name, with a line for each issue, 

207 and the panels share their axes. 

208 

209 """ 

210 

211 size: ClassVar[tuple[float, float]] = (9.6, 7.2) 

212 shared_axes: ClassVar[str] = 'xy' 

213 starts_at_zero: ClassVar[str] = 'y' 

214 

215 """ Required Methods """ 

216 

217 def draw( 

218 self, 

219 item: amos.Dataset, 

220 figure: Any, 

221 *, 

222 issues: Sequence[str] | str = (), 

223 year: str = 'year', 

224 court_name: str = 'court_name', 

225 court_num: str = 'court_num', 

226 jurisdiction: str = 'federal', 

227 columns: int = 4, 

228 **kwargs: Any) -> None: 

229 """Draws the number of cases with each issue in each court and year. 

230 

231 Args: 

232 item: the cases. 

233 figure: the figure to draw on. 

234 issues: the columns of flags to count, as a list or a 

235 comma-separated `str`. Required. 

236 year: the column with each case's year. Defaults to "year". 

237 court_name: the column with courtpy's name for each case's court. 

238 Defaults to "court_name". 

239 court_num: the column with courtpy's number for each case's 

240 court. Defaults to "court_num". 

241 jurisdiction: the folder of the jurisdiction's table of courts. 

242 Defaults to "federal". 

243 columns: the most panels in a row. Defaults to 4. 

244 **kwargs: not used. 

245 

246 Raises: 

247 ValueError: if no issue is named. 

248 KeyError: if an issue is not a column of the cases. 

249 

250 """ 

251 data = item.data 

252 named = utilities.listify(issues) 

253 if not named: 

254 message = 'issues_over_time needs "issues": columns of flags' 

255 raise ValueError(message) 

256 cases.require_columns(data, named, 'issues_over_time') 

257 counts = { 

258 issue: _yearly( 

259 data, cases.column_as_flags(data, issue).astype('int64'), 

260 year = year, court_name = court_name, court_num = court_num, 

261 jurisdiction = jurisdiction, how = 'sum') 

262 for issue in named} 

263 every = counts[named[0]].index 

264 panels = _court_panels(figure, every, columns) 

265 for issue, table in counts.items(): 

266 years = table.columns.to_numpy() 

267 for court, axes in panels.items(): 

268 axes.plot( 

269 years, table.loc[court].to_numpy(), marker = '.', 

270 label = _words(issue)) 

271 first = next(iter(panels.values())) 

272 handles, labels = first.get_legend_handles_labels() 

273 figure.legend( 

274 handles, labels, loc = 'outside upper center', 

275 ncols = min(len(named), 4)) 

276 figure.supxlabel('Year') 

277 figure.supylabel('Cases') 

278 

279 

280@dataclasses.dataclass 

281class PanelComposition(amos.plots.Plot): 

282 """Plots the rate of a column for each composition of the panel. 

283 

284 A panel's composition is the party of the president who appointed each 

285 of its judges, from all Democratic appointees ("DDD") to all Republican 

286 ones ("RRR") for a panel of three (see 

287 `courtpy.judges.panel_compositions`). With "by", the cases are split by 

288 another column (such as "type_criminal"), with bars side by side. 

289 

290 """ 

291 

292 starts_at_zero: ClassVar[str] = 'y' 

293 

294 """ Required Methods """ 

295 

296 def draw( 

297 self, 

298 item: amos.Dataset, 

299 figure: Any, 

300 *, 

301 column: str | None = None, 

302 by: str | None = None, 

303 size: int = 3, 

304 **kwargs: Any) -> None: 

305 """Draws the rate of `column` for each composition of the panel. 

306 

307 Args: 

308 item: the cases, with the parties of their judges. 

309 figure: the figure to draw on. 

310 column: the column whose rate is drawn. Defaults to `None`, which 

311 uses the dataset's label, or else `_DEFAULT_RATE`. 

312 by: a column to split the cases by. A column of flags splits them 

313 into those with the flag and the others. Defaults to `None`. 

314 size: the number of judges on the panels to draw. Defaults to 3. 

315 **kwargs: not used. 

316 

317 """ 

318 data = item.data 

319 column = _rate_column(item, column) 

320 table = pd.DataFrame({ 

321 'composition': judges.panel_compositions(data, size), 

322 'value': _numbers(data[column]), 

323 'group': _groups(data, by)}).dropna() 

324 rates = table.groupby( 

325 ['group', 'composition'], observed = False)['value'].agg( 

326 ['mean', 'size']) 

327 groups = list(dict.fromkeys(rates.index.get_level_values('group'))) 

328 names = list(table['composition'].cat.categories) 

329 axes = figure.subplots() 

330 width = 0.8 / len(groups) 

331 for place, group in enumerate(groups): 

332 found = rates.loc[group].reindex(names) 

333 spots = np.arange(len(names)) + (place - (len(groups) - 1) / 2) * ( 

334 width) 

335 bars = axes.bar( 

336 spots, found['mean'].fillna(0).to_numpy(), width, 

337 label = group if by else None) 

338 for bar, count in zip( 

339 bars, found['size'].fillna(0), strict = True): 

340 if count: 

341 axes.annotate( 

342 f'n = {int(count):,}', 

343 (bar.get_x() + bar.get_width() / 2, bar.get_height()), 

344 ha = 'center', va = 'bottom', fontsize = 'x-small') 

345 shares = _is_share(table['value']) 

346 axes.set_xticks(np.arange(len(names)), names) 

347 axes.set_xlabel('Panel (D: Democratic appointee, R: Republican)') 

348 axes.set_ylabel(_rate_name(column, shares)) 

349 _as_percent(axes.yaxis, shares) 

350 if by: 350 ↛ exitline 350 didn't return from function 'draw' because the condition on line 350 was always true

351 axes.legend(title = _words(by)) 

352 

353 

354@dataclasses.dataclass 

355class LowerCourtRates(amos.plots.Plot): 

356 """Plots the rate of a column for each court below, by reviewing court. 

357 

358 Each court whose decisions the courts in the data reviewed (such as each 

359 district court of a circuit) has a bar, with the number of its cases. 

360 The bars are grouped and colored by the reviewing court, in the order of 

361 the table of courts, so that a court of appeals' treatment of its 

362 districts can be compared. 

363 

364 """ 

365 

366 size: ClassVar[tuple[float, float]] = (7.2, 9.6) 

367 starts_at_zero: ClassVar[str] = 'x' 

368 

369 """ Required Methods """ 

370 

371 def draw( 

372 self, 

373 item: amos.Dataset, 

374 figure: Any, 

375 *, 

376 column: str | None = None, 

377 minimum: int = 1, 

378 court_name: str = 'court_name', 

379 court_num: str = 'court_num', 

380 lower_court_name: str = 'lower_court_name', 

381 lower_court_num: str = 'lower_court_num', 

382 jurisdiction: str = 'federal', 

383 **kwargs: Any) -> None: 

384 """Draws the rate of `column` for each court below. 

385 

386 Args: 

387 item: the cases. 

388 figure: the figure to draw on. 

389 column: the column whose rate is drawn. Defaults to `None`, which 

390 uses the dataset's label, or else `_DEFAULT_RATE`. 

391 minimum: the fewest cases of a court below to draw it. Defaults 

392 to 1. 

393 court_name: the column with courtpy's name for each case's court. 

394 Defaults to "court_name". 

395 court_num: the column with courtpy's number for each case's 

396 court. Defaults to "court_num". 

397 lower_court_name: the column with courtpy's name for the court 

398 below. Defaults to "lower_court_name". 

399 lower_court_num: the column with courtpy's number for the court 

400 below. Defaults to "lower_court_num". 

401 jurisdiction: the folder of the jurisdiction's table of courts. 

402 Defaults to "federal". 

403 **kwargs: not used. 

404 

405 """ 

406 data = item.data 

407 column = _rate_column(item, column) 

408 table = pd.DataFrame({ 

409 'court': courts.court_labels( 

410 data, court_name = court_name, court_num = court_num, 

411 jurisdiction = jurisdiction), 

412 'lower': courts.court_labels( 

413 data, court_name = lower_court_name, 

414 court_num = lower_court_num, jurisdiction = jurisdiction), 

415 'value': _numbers(data[column])}).dropna() 

416 shares = _is_share(table['value']) 

417 rates = table.groupby(['court', 'lower'], observed = True)[ 

418 'value'].agg(['mean', 'size']) 

419 rates = rates[rates['size'] >= minimum] 

420 axes = figure.subplots() 

421 places = np.arange(len(rates)) 

422 reviewing = rates.index.get_level_values('court') 

423 for number, court in enumerate(dict.fromkeys(reviewing)): 

424 rows = reviewing == court 

425 axes.barh( 

426 places[rows], rates['mean'].to_numpy()[rows], 

427 color = f'C{number % 10}', label = str(court)) 

428 lowers = rates.index.get_level_values('lower') 

429 axes.set_yticks( 

430 places, 

431 [f'{lower} ({int(n):,})' 

432 for lower, n in zip(lowers, rates['size'], strict = True)], 

433 fontsize = 'x-small') 

434 axes.invert_yaxis() 

435 axes.set_xlabel(_rate_name(column, shares)) 

436 _as_percent(axes.xaxis, shares) 

437 figure.legend( 

438 title = 'Reviewing court', loc = 'outside lower center', 

439 ncols = 3, fontsize = 'small') 

440 

441 

442@dataclasses.dataclass 

443class TrendsByAdministration(amos.plots.Plot): 

444 """Plots the yearly rate of a column in each court, with presidents. 

445 

446 Each court in the data has a panel with the yearly rate, and the 

447 background of every panel is shaded by the party of the president in 

448 office (blue for a Democrat and red for a Republican; see 

449 `courtpy.politics.executives`). 

450 

451 """ 

452 

453 size: ClassVar[tuple[float, float]] = (9.6, 7.2) 

454 shared_axes: ClassVar[str] = 'xy' 

455 starts_at_zero: ClassVar[str] = 'y' 

456 

457 """ Required Methods """ 

458 

459 def draw( 

460 self, 

461 item: amos.Dataset, 

462 figure: Any, 

463 *, 

464 column: str | None = None, 

465 year: str = 'year', 

466 court_name: str = 'court_name', 

467 court_num: str = 'court_num', 

468 jurisdiction: str = 'federal', 

469 columns: int = 4, 

470 **kwargs: Any) -> None: 

471 """Draws the yearly rate of `column` in each court. 

472 

473 Args: 

474 item: the cases. 

475 figure: the figure to draw on. 

476 column: the column whose rate is drawn. Defaults to `None`, which 

477 uses the dataset's label, or else `_DEFAULT_RATE`. 

478 year: the column with each case's year. Defaults to "year". 

479 court_name: the column with courtpy's name for each case's court. 

480 Defaults to "court_name". 

481 court_num: the column with courtpy's number for each case's 

482 court. Defaults to "court_num". 

483 jurisdiction: the folder of the jurisdiction's table of courts. 

484 Defaults to "federal". 

485 columns: the most panels in a row. Defaults to 4. 

486 **kwargs: not used. 

487 

488 """ 

489 data = item.data 

490 column = _rate_column(item, column) 

491 rates = _yearly( 

492 data, _numbers(data[column]), year = year, 

493 court_name = court_name, court_num = court_num, 

494 jurisdiction = jurisdiction, how = 'mean') 

495 shares = _is_share(_numbers(data[column])) 

496 years = rates.columns.to_numpy(dtype = float) 

497 terms = _terms(years.min(), years.max() + 1) 

498 panels = _court_panels(figure, rates.index, columns) 

499 patch = amos.utilities.import_tool('matplotlib.patches').Patch 

500 for court, axes in panels.items(): 

501 for start, end, party in terms: 

502 axes.axvspan( 

503 start, end, color = _PARTY_COLORS[party], alpha = 0.12, 

504 linewidth = 0) 

505 axes.plot( 

506 years, rates.loc[court].to_numpy(), color = '0.15', 

507 marker = '.') 

508 _as_percent(axes.yaxis, shares) 

509 figure.legend( 

510 handles = [ 

511 patch(color = _PARTY_COLORS[-1], alpha = 0.3, 

512 label = 'Democratic president'), 

513 patch(color = _PARTY_COLORS[1], alpha = 0.3, 

514 label = 'Republican president')], 

515 loc = 'outside upper center', ncols = 2) 

516 figure.supxlabel('Year') 

517 figure.supylabel(_rate_name(column, shares)) 

518 

519 

520@dataclasses.dataclass 

521class IdbConfusionMatrices(amos.plots.Plot): 

522 """Plots how the data agrees with the Integrated Database, by variable. 

523 

524 Each variable of `compare_with_idb`'s first table is a panel with a 

525 confusion matrix: the data's value (true or false) in the rows and the 

526 database's in the columns, each cell shaded by its share of the dockets 

527 compared and labeled with its count and share. The panel's title has 

528 Cohen's kappa. 

529 

530 """ 

531 

532 size: ClassVar[tuple[float, float]] = (8.0, 6.0) 

533 starts_at_zero: ClassVar[str] = '' 

534 

535 """ Required Methods """ 

536 

537 def draw( 

538 self, 

539 item: amos.Dataset, 

540 figure: Any, 

541 *, 

542 source: str = 'compare_with_idb', 

543 columns: int = 3, 

544 **kwargs: Any) -> None: 

545 """Draws a confusion matrix for each variable. 

546 

547 Args: 

548 item: the dataset, with the table of `compare_with_idb`. 

549 figure: the figure to draw on. 

550 source: the name of the table in the dataset's `tables`. Defaults 

551 to "compare_with_idb". 

552 columns: the most panels in a row. Defaults to 3. 

553 **kwargs: not used. 

554 

555 """ 

556 table = _table(item, source) 

557 panels = _court_panels(figure, table.index, columns, share_y = False) 

558 labels = ['True', 'False'] 

559 for name, axes in panels.items(): 

560 row = table.loc[name] 

561 counts = np.array([ 

562 [row['both_true'], row['data_only']], 

563 [row['idb_only'], row['both_false']]], dtype = float) 

564 total = counts.sum() 

565 shares = counts / total if total else counts 

566 axes.imshow(shares, cmap = 'Blues', vmin = 0, vmax = 1) 

567 for (down, across), count in np.ndenumerate(counts): 

568 share = shares[down, across] 

569 axes.text( 

570 across, down, f'{count:,.0f}\n{share:.0%}', 

571 ha = 'center', va = 'center', fontsize = 'small', 

572 color = 'white' if share > 0.6 else 'black') 

573 axes.set_xticks([0, 1], labels) 

574 axes.set_yticks([0, 1], labels) 

575 axes.set_xlabel('IDB', fontsize = 'small') 

576 axes.set_ylabel('Data', fontsize = 'small') 

577 axes.minorticks_off() 

578 kappa = row['kappa'] 

579 title = _words(str(name)) 

580 if pd.notna(kappa): 580 ↛ 582line 580 didn't jump to line 582 because the condition on line 580 was always true

581 title = f'{title} (κ = {kappa:.2f})' 

582 axes.set_title(title, fontsize = 'small') 

583 

584 

585@dataclasses.dataclass 

586class IdbMissingDifferences(amos.plots.Plot): 

587 """Plots how the appeals that the data lacks differ, by group. 

588 

589 `compare_with_idb`'s second table is drawn as a grid of the groups 

590 (circuits or districts, with "All" first) and the variables. Each cell 

591 is the share of the appeals that the data has minus the share of those 

592 that it lacks, in percentage points, shaded red where the data has more 

593 and blue where it has less, with a star if the p value of the difference 

594 is below "alpha". Each group's label says what share of its appeals the 

595 data has. 

596 

597 """ 

598 

599 size: ClassVar[tuple[float, float]] = (9.0, 7.0) 

600 starts_at_zero: ClassVar[str] = '' 

601 

602 """ Required Methods """ 

603 

604 def draw( 

605 self, 

606 item: amos.Dataset, 

607 figure: Any, 

608 *, 

609 source: str = 'compare_with_idb_missing', 

610 alpha: float = 0.05, 

611 **kwargs: Any) -> None: 

612 """Draws the differences of each variable in each group. 

613 

614 Args: 

615 item: the dataset, with the second table of `compare_with_idb`. 

616 figure: the figure to draw on. 

617 source: the name of the table in the dataset's `tables`. Defaults 

618 to "compare_with_idb_missing". 

619 alpha: the p value below which a difference is starred. Defaults 

620 to 0.05. 

621 **kwargs: not used. 

622 

623 """ 

624 table = _table(item, source) 

625 groups = list(dict.fromkeys(table['group'])) 

626 names = list(dict.fromkeys(table['variable'])) 

627 differences = table.pivot_table( 

628 index = 'group', columns = 'variable', values = 'difference', 

629 aggfunc = 'first', dropna = False).reindex( 

630 index = groups, columns = names) 

631 p_values = table.pivot_table( 

632 index = 'group', columns = 'variable', values = 'p_value', 

633 aggfunc = 'first', dropna = False).reindex( 

634 index = groups, columns = names) 

635 coverage = table.drop_duplicates('group').set_index('group')[ 

636 'coverage'].reindex(groups) 

637 points = differences.to_numpy(dtype = float) * 100 

638 significance = p_values.to_numpy(dtype = float) 

639 largest = np.nanmax(np.abs(points)) if np.isfinite(points).any() else 1 

640 axes = figure.subplots() 

641 image = axes.imshow( 

642 points, cmap = 'RdBu_r', vmin = -largest, vmax = largest, 

643 aspect = 'auto') 

644 for (down, across), value in np.ndenumerate(points): 

645 if np.isnan(value): 645 ↛ 646line 645 didn't jump to line 646 because the condition on line 645 was never true

646 continue 

647 starred = significance[down, across] < float(alpha) 

648 axes.text( 

649 across, down, f'{value:+.0f}' + ('*' if starred else ''), 

650 ha = 'center', va = 'center', fontsize = 'small', 

651 color = 'white' if abs(value) > 0.6 * largest else 'black') 

652 axes.set_xticks( 

653 range(len(names)), [_words(str(n)) for n in names], 

654 rotation = 45, ha = 'right') 

655 axes.set_yticks(range(len(groups)), [ 

656 f'{group} ({share:.0%} in data)' if pd.notna(share) 

657 else str(group) 

658 for group, share in coverage.items()]) 

659 axes.minorticks_off() 

660 colorbar = figure.colorbar(image, ax = axes) 

661 colorbar.set_label( 

662 'Share in data minus share missing (points)', fontsize = 'small') 

663 axes.set_title( 

664 f'* p < {float(alpha):g}', fontsize = 'small', loc = 'right') 

665 

666 

667@dataclasses.dataclass 

668class JudgeNetwork(amos.plots.Plot): 

669 """Plots the judges as a network of who sat with, or dissented from, whom. 

670 

671 Each judge is a node, colored by the party of the president who 

672 appointed the judge (gray if it is not known), and two judges are joined 

673 by a line whose width is how many cases they decided together. With 

674 "dissents", two judges are joined only by the cases in which one of them 

675 dissented and the other did not, so the lines show who dissented from 

676 whom. 

677 

678 """ 

679 

680 size: ClassVar[tuple[float, float]] = (8.0, 8.0) 

681 starts_at_zero: ClassVar[str] = '' 

682 

683 """ Required Methods """ 

684 

685 def draw( 

686 self, 

687 item: amos.Dataset, 

688 figure: Any, 

689 *, 

690 dissents: bool = False, 

691 minimum: int = 1, 

692 labels: bool = True, 

693 judge: str = 'judge', 

694 case: str = 'case_id', 

695 party: str = 'judge_party', 

696 dissented: str = 'judge_dissented', 

697 seed: int = 0, 

698 **kwargs: Any) -> None: 

699 """Draws the network of the judges. 

700 

701 Args: 

702 item: the votes (see `cases_to_votes`), a row for each judge on 

703 each case. 

704 figure: the figure to draw on. 

705 dissents: whether to join judges by the dissents of one from the 

706 other, instead of by the cases they decided together. 

707 Defaults to `False`. 

708 minimum: the fewest cases that join two judges to draw the line 

709 between them. Defaults to 1. 

710 labels: whether to write each judge's name. Defaults to `True`. 

711 judge: the column with each judge's name. Defaults to "judge". 

712 case: the column with each vote's case. Defaults to "case_id". 

713 party: the column with the party of the president who appointed 

714 the judge (-1 or 1). Defaults to "judge_party". 

715 dissented: the column of flags of whether the judge dissented, 

716 for `dissents`. Defaults to "judge_dissented". 

717 seed: the seed of the layout, so that the same data is drawn the 

718 same way. Defaults to 0. 

719 **kwargs: not used. 

720 

721 Raises: 

722 KeyError: if the votes lack a column that is needed. 

723 

724 """ 

725 networkx = amos.utilities.import_tool('networkx') 

726 data = item.data 

727 needed = [judge, case, *([dissented] if dissents else [])] 

728 cases.require_columns( 

729 data, needed, 'judge_network (make votes with cases_to_votes)') 

730 pairs = _pairs(data, judge, case, dissented if dissents else None) 

731 pairs = pairs[pairs['cases'] >= minimum] 

732 graph = networkx.Graph() 

733 graph.add_nodes_from(data[judge].dropna().astype(str).unique()) 

734 graph.add_weighted_edges_from( 

735 pairs[['first', 'second', 'cases']].itertuples(index = False)) 

736 parties = ( 

737 pd.to_numeric(data[party], errors = 'coerce').groupby( 

738 data[judge].astype(str)).first() 

739 if party in data.columns else pd.Series(dtype = float)) 

740 colors = [ 

741 _PARTY_COLORS.get(int(parties[n]), '0.6') 

742 if n in parties.index and not pd.isna(parties[n]) else '0.6' 

743 for n in graph.nodes] 

744 weights = np.array( 

745 [graph.edges[e]['weight'] for e in graph.edges], dtype = float) 

746 widths = 0.5 + 3.5 * weights / weights.max() if len(weights) else [] 

747 axes = figure.subplots() 

748 layout = networkx.spring_layout(graph, seed = seed, weight = 'weight') 

749 networkx.draw_networkx_edges( 

750 graph, layout, ax = axes, width = widths, edge_color = '0.6', 

751 alpha = 0.7) 

752 networkx.draw_networkx_nodes( 

753 graph, layout, ax = axes, node_color = colors, node_size = 120) 

754 if labels: 754 ↛ 757line 754 didn't jump to line 757 because the condition on line 754 was always true

755 networkx.draw_networkx_labels( 

756 graph, layout, ax = axes, font_size = 6) 

757 axes.set_axis_off() 

758 

759 

760""" Private Functions """ 

761 

762 

763def _amount(value: float, shares: bool) -> str: 

764 """Returns a rate as text for a label. 

765 

766 Args: 

767 value: the rate. 

768 shares: whether the rate is a share (of cases with a flag). 

769 

770 Returns: 

771 The rate as a percent (such as "17%") if it is a share, and otherwise 

772 to two decimal places. 

773 

774 """ 

775 return f'{value:.0%}' if shares else f'{value:.2f}' 

776 

777 

778def _as_percent(axis: Any, shares: bool) -> None: 

779 """Writes the ticks of an axis of shares as percents. 

780 

781 Args: 

782 axis: the axis (such as `axes.xaxis`). 

783 shares: whether the axis shows shares; if not, it is unchanged. 

784 

785 """ 

786 if shares: 786 ↛ exitline 786 didn't return from function '_as_percent' because the condition on line 786 was always true

787 ticker = amos.utilities.import_tool('matplotlib.ticker') 

788 axis.set_major_formatter(ticker.PercentFormatter(1.0, decimals = 0)) 

789 

790 

791def _court_panels( 

792 figure: Any, 

793 names: Sequence[Any] | pd.Index, 

794 columns: int, 

795 *, 

796 share_y: bool = True) -> dict[Any, Any]: 

797 """Makes a panel for each court on a figure. 

798 

799 Args: 

800 figure: the figure to draw on. 

801 names: the courts' labels, in order. 

802 columns: the most panels in a row. 

803 share_y: whether the panels share the range of the y axis. Defaults 

804 to `True`. 

805 

806 Returns: 

807 The axes of each court's panel, by its label, each titled with it. 

808 Panels left over in the last row are hidden. 

809 

810 """ 

811 names = list(names) 

812 across = max(1, min(columns, len(names))) 

813 down = max(1, math.ceil(len(names) / across)) 

814 grid = figure.subplots( 

815 down, across, sharex = True, sharey = share_y, squeeze = False) 

816 panels: dict[Any, Any] = {} 

817 for name, axes in itertools.zip_longest(names, grid.flat): 

818 if name is None: 

819 axes.set_visible(False) 

820 continue 

821 axes.set_title(str(name), fontsize = 'small') 

822 panels[name] = axes 

823 return panels 

824 

825 

826def _groups(data: pd.DataFrame, by: str | None) -> pd.Series: 

827 """Returns the group of each case for a plot split by a column. 

828 

829 Args: 

830 data: the cases. 

831 by: the column to split them by, or `None`. 

832 

833 Raises: 

834 KeyError: if `by` is not a column of the cases. 

835 

836 Returns: 

837 The group of each case as text: "all cases" without `by`, the 

838 column's name and "other" for a column of flags, and the 

839 column's values otherwise. 

840 

841 """ 

842 if by is None: 842 ↛ 843line 842 didn't jump to line 843 because the condition on line 842 was never true

843 return pd.Series('all cases', index = data.index) 

844 cases.require_columns(data, [by], 'the column to split by') 

845 values = data[by] 

846 if pd.api.types.is_bool_dtype(values.dtype) or values.dropna().isin( 846 ↛ 850line 846 didn't jump to line 850 because the condition on line 846 was always true

847 [True, False]).all(): 

848 flags = cases.column_as_flags(data, by) 

849 return flags.map({True: _words(by), False: 'other'}) 

850 return values.astype('string') 

851 

852 

853def _numbers(values: pd.Series) -> pd.Series: 

854 """Returns a column as numbers, so that its mean is its rate. 

855 

856 Args: 

857 values: a column of flags or numbers, which may be missing. 

858 

859 Returns: 

860 The values as decimals (1 for true and 0 for false), with missing 

861 values kept missing. 

862 

863 """ 

864 if values.dtype == object: 864 ↛ 865line 864 didn't jump to line 865 because the condition on line 864 was never true

865 values = values.map( 

866 lambda v: float(v) if isinstance(v, bool | int | float) else v) 

867 if pd.api.types.is_bool_dtype(values.dtype): 867 ↛ 869line 867 didn't jump to line 869 because the condition on line 867 was always true

868 return values.astype('Float64').astype(float) 

869 return pd.to_numeric(values, errors = 'coerce').astype(float) 

870 

871 

872def _pairs( 

873 data: pd.DataFrame, 

874 judge: str, 

875 case: str, 

876 dissented: str | None) -> pd.DataFrame: 

877 """Returns how many cases join each pair of judges. 

878 

879 Args: 

880 data: the votes, a row for each judge on each case. 

881 judge: the column with each judge's name. 

882 case: the column with each vote's case. 

883 dissented: the column of flags of whether each judge dissented, to 

884 count only the cases in which one judge of the pair dissented and 

885 the other did not, or `None` to count every case the pair 

886 decided together. 

887 

888 Returns: 

889 A table with "first" and "second" (the pair's names, in alphabetical 

890 order) and "cases". 

891 

892 """ 

893 votes = pd.DataFrame({ 

894 'case': data[case], 

895 'judge': data[judge].astype('string'), 

896 'dissented': ( 

897 cases.column_as_flags(data, dissented) if dissented 

898 else pd.Series(False, index = data.index))}).dropna( 

899 subset = ['case', 'judge']) 

900 joined = votes.merge(votes, on = 'case', suffixes = ('_a', '_b')) 

901 joined = joined[joined['judge_a'] < joined['judge_b']] 

902 if dissented: 

903 joined = joined[joined['dissented_a'] != joined['dissented_b']] 

904 counted = joined.groupby(['judge_a', 'judge_b']).size() 

905 return counted.rename('cases').reset_index().rename( 

906 columns = {'judge_a': 'first', 'judge_b': 'second'}) 

907 

908 

909def _is_share(values: pd.Series) -> bool: 

910 """Returns whether a column's rate is a share of cases. 

911 

912 Args: 

913 values: the column, as numbers. 

914 

915 Returns: 

916 Whether every value that is not missing is 0 or 1 (a flag), so that 

917 its mean is the share of the cases that have it. 

918 

919 """ 

920 return bool(values.dropna().isin([0, 1]).all()) 

921 

922 

923def _rate_column(item: amos.Dataset, column: str | None) -> str: 

924 """Returns the column whose rate a plot draws. 

925 

926 Args: 

927 item: the cases. 

928 column: the column named in the plot's parameters, or `None`. 

929 

930 Raises: 

931 KeyError: if the column is not in the data. 

932 

933 Returns: 

934 `column`, or else the dataset's label, or else `_DEFAULT_RATE`. 

935 

936 """ 

937 chosen = column or item.label or _DEFAULT_RATE 

938 cases.require_columns(item.data, [chosen], 'the column of the rate') 

939 return str(chosen) 

940 

941 

942def _rate_name(column: str, shares: bool) -> str: 

943 """Returns the name of the axis of a rate. 

944 

945 Args: 

946 column: the column whose rate is drawn. 

947 shares: whether the rate is a share of cases. 

948 

949 Returns: 

950 "Share of cases: ..." for a share, and "Mean: ..." otherwise. 

951 

952 """ 

953 kind = 'Share of cases' if shares else 'Mean' 

954 return f'{kind}: {_words(column)}' 

955 

956 

957def _terms(start: float, stop: float) -> list[tuple[float, float, int]]: 

958 """Returns the presidents' terms between two years, by party. 

959 

960 Args: 

961 start: the first year. 

962 stop: the year after the last one. 

963 

964 Returns: 

965 The start and end of each term (as decimal years, cut to the range) 

966 and the party of the president (-1 or 1), leaving out a term of 

967 another party. 

968 

969 """ 

970 

971 def decimal(day: pd.Timestamp) -> float: 

972 """Returns a day as a year with a fraction. 

973 

974 Args: 

975 day: the day. 

976 

977 Returns: 

978 The year, plus the share of it that came before the day. 

979 

980 """ 

981 return day.year + (day.dayofyear - 1) / 365.25 

982 

983 terms = politics.executives() 

984 parties = pd.to_numeric(terms['executive_ideology'], errors = 'coerce') 

985 found: list[tuple[float, float, int]] = [] 

986 for party, began, ended in zip( 

987 parties.tolist(), pd.to_datetime(terms['start_date']), 

988 pd.to_datetime(terms['end_date']), strict = True): 

989 if pd.isna(party) or int(party) not in _PARTY_COLORS: 989 ↛ 990line 989 didn't jump to line 990 because the condition on line 989 was never true

990 continue 

991 begins = decimal(began) 

992 ends = stop if pd.isna(ended) else decimal(ended) 

993 if ends > start and begins < stop: 

994 found.append((max(begins, start), min(ends, stop), int(party))) 

995 return found 

996 

997 

998def _table(item: amos.Dataset, source: str) -> pd.DataFrame: 

999 """Returns a table of a dataset's `tables` to draw. 

1000 

1001 Args: 

1002 item: the dataset. 

1003 source: the name of the table. 

1004 

1005 Raises: 

1006 KeyError: if the dataset has no table named `source`. 

1007 

1008 Returns: 

1009 The table. 

1010 

1011 """ 

1012 if source not in item.tables: 1012 ↛ 1013line 1012 didn't jump to line 1013 because the condition on line 1012 was never true

1013 message = ( 

1014 f'there is no table named {source!r} to draw (apply ' 

1015 f'"compare_with_idb" first, or name its table as "source")' 

1016 ) 

1017 raise KeyError(message) 

1018 return item.tables[source] 

1019 

1020 

1021def _words(column: str) -> str: 

1022 """Returns the name of a column as words for a figure. 

1023 

1024 Args: 

1025 column: the column's name, such as "outcome_reversal". 

1026 

1027 Returns: 

1028 The name with spaces for underscores, such as "outcome reversal". 

1029 

1030 """ 

1031 return str(column).replace('_', ' ') 

1032 

1033 

1034def _yearly( 

1035 data: pd.DataFrame, 

1036 values: pd.Series, 

1037 *, 

1038 year: str, 

1039 court_name: str, 

1040 court_num: str, 

1041 jurisdiction: str, 

1042 how: Literal['sum', 'mean']) -> pd.DataFrame: 

1043 """Returns a summary of values for each court in each year. 

1044 

1045 Args: 

1046 data: the cases. 

1047 values: a value for each case. 

1048 year: the column with each case's year. 

1049 court_name: the column with courtpy's name for each case's court. 

1050 court_num: the column with courtpy's number for each case's court. 

1051 jurisdiction: the folder of the jurisdiction's table of courts. 

1052 how: how to summarize each court's values in a year ("sum" or 

1053 "mean"). 

1054 

1055 Raises: 

1056 KeyError: if the cases have no `year` column. 

1057 

1058 Returns: 

1059 A table with a row for each court (by its label, in order) and a 

1060 column for each year from the first to the last, with 0 for a 

1061 sum (and missing for a mean) where a court has no cases. 

1062 

1063 """ 

1064 cases.require_columns(data, [year], 'a plot over time') 

1065 table = pd.DataFrame({ 

1066 'court': courts.court_labels( 

1067 data, court_name = court_name, court_num = court_num, 

1068 jurisdiction = jurisdiction), 

1069 'year': pd.to_numeric(data[year], errors = 'coerce'), 

1070 'value': values}).dropna(subset = ['court', 'year']) 

1071 table['year'] = table['year'].astype('int64') 

1072 summary = table.pivot_table( 

1073 index = 'court', columns = 'year', values = 'value', aggfunc = how, 

1074 observed = True) 

1075 years = range(int(table['year'].min()), int(table['year'].max()) + 1) 

1076 summary = summary.reindex(columns = years) 

1077 return summary.fillna(0) if how == 'sum' else summary