Skip to content

O0000-code/SSCI-Plots

Repository files navigation

SSCI-Plots

Publication-ready matplotlib styles for SSCI / SCI journal submissions.

License: MIT Python matplotlib Journals Stars

简体中文 README

Same data, two styles: default matplotlib on the left, apply_style(journal="apa") on the right

Gallery · Install · What's included · Python library

One call, publication-ready figure.

  • 🎯 12 journal presetsapply_style(journal="lancet") configures matplotlib to match a journal's house style. APA, Elsevier, Wiley, SAGE, Psychological Science, OUP / ASA, Nature, Science, NEJM, Lancet, BMJ, JAMA.
  • 🎨 21 color-blind-safe palettes — drawn from Tol, Okabe-Ito, ggsci, MetBrewer, Economist, BBC. Fonts are embedded, Latin statistics italicized.
  • 🧰 27 helpers — significance brackets, inline statistics, reference lines, and multi-panel composition (compose_grid, small_multiples, shared colorbar / legend, inset zoom).
  • 📄 APA 7 output — image file plus a separate Markdown caption. Figure number, title, and Note stay out of the image itself.
  • 🌐 Cross-disciplinary — psychology, economics, public health, sociology, political science, geography, education, methodology.

Gallery

Eighteen worked examples grouped by discipline. Switch presets by changing one argument to apply_style(). To regenerate locally: python examples/generate_examples.py.

🧠 Psychology classics

Grouped bar with significance brackets, mediation diagram, correlation heatmap, interaction plot, and raincloud.

APA preset: grouped bar chart with significance brackets and pairwise Cohen's d
apa · Bar chart with significance brackets
Anxiety scores across three intervention arms, with pairwise effect sizes and an omnibus F test.
Elsevier preset: mediation diagram X to M to Y with a, b, and c-prime paths
elsevier · Mediation diagram (XMY)
Self-esteem to GPA via academic self-efficacy. Reports the a, b, and c' paths plus the indirect effect with bootstrap 95% CI.
Wiley preset: lower-triangle correlation heatmap with internalizing and positive subscales
wiley · Lower-triangle correlation heatmap
Six variables grouped into an internalizing subscale and a positive subscale. Pearson r in each cell with significance asterisks.
OUP preset: 2 by 2 interaction plot of stress and social support on wellbeing
asa · Stress × support interaction
How perceived stress predicts wellbeing differently under high vs. low social support, with simple-slope estimates for each level.
APA preset: raincloud plot of cognitive performance across three SES groups
apa · Raincloud plot (three SES groups)
Cognitive performance by SES band, showing the density, the box summary, and the raw observations on a single axis (Allen et al., 2019).

📊 Meta-analysis & methodology

Forest plot, multi-panel composite, and specification curve.

Psychological Science preset: forest plot with three subgroups and random-effects diamonds
psych_science · Forest plot with subgroups
Ten mindfulness studies pooled with random effects, broken out by age band. Reports subgroup diamonds, overall effect, 95% prediction interval, and I2.
APA preset: 1x3 multi-panel composite with scatter, boxplot, and time-series
apa · Multi-panel composite (A / B / C)
Three related views of one study: scatter with CI, cross-group boxplot, and a treatment-vs-control time series, with consistent styling across panels.
APA preset: specification curve with 64 specifications and binary descriptor matrix
apa · Specification curve
Effect of X on Y across 64 analytic specifications, with the matrix below showing which analytic choices produced each estimate.

💰 Causal inference & economics

Event-study DID, regression discontinuity, mobility transition matrix, and a multi-model coefficient plot.

Economics preset: event-study DID plot showing pre- and post-policy coefficients with a confidence band
economics · Event-study DID
Treatment effects of a minimum-wage policy on teen employment, plotted over event time with a confidence band and a pre-trend placebo test.
Economics preset: regression discontinuity plot with fits on either side of a cutoff and a McCrary density inset
economics · Regression discontinuity
College enrolment around a scholarship test-score cutoff, with the RD estimate, bias-corrected CI, and a McCrary density check on the running variable.
Intergenerational mobility transition matrix with viridis colormap and diagonal annotations
apa · Intergenerational mobility matrix
Probability of a child's education level given a parent's, with marginal totals and the lowest-mobility cell highlighted.
APA preset: multi-model coefficient plot across three model specifications
apa · Multi-model coefficient plot
Same covariates estimated under three nested specifications side by side, with covariate groups banded and model fit reported per panel.

🌍 Clinical, political, geography & education

Survival curve, ideological scaling, geographic distribution, and growth trajectories.

NEJM preset: Kaplan-Meier survival curve with at-risk table and zoom inset
nejm · Kaplan-Meier survival curve
Five-year survival in a two-arm cancer trial, with hazard ratio, log-rank p, an at-risk table, and a zoom on the early follow-up window.
APA preset: DW-NOMINATE ideological scaling KDE for senators and donors by party
apa · Ideological scaling
DW-NOMINATE distributions for senators and their donors, with named legislators annotated and a rug strip showing individual scores.
APA preset: US state-level mobility map with a validation scatter inset
apa · US state mobility map
Income mobility across US states, with regional patterns annotated and a validation scatter against administrative records.
APA preset: 2x2 SES-faceted growth curves with individual trajectories and group mean
apa · Growth curves by SES quartile
Student literacy trajectories from Grades 3–8, faceted by SES quartile. Individual paths sit behind the group mean with a 95% CI band.

🎯 Capstone: research dashboard

APA preset: six-panel heterogeneous research dashboard with mixed chart types
apa · Six-panel research dashboard
One mindfulness trial summarised across six panels: study design, baseline correlation, measure intercorrelations, survival, subgroup effects, and robustness across specifications.

Why this exists

I used to spend hours on every submission tuning matplotlib by hand: font size, spines, palette, column width. Reviewers still flagged the figures. So I sat down with the author guidelines for APA, Elsevier, Wiley, SAGE, OUP, Nature, Science, NEJM, Lancet, BMJ, and JAMA, read the color-vision-deficiency papers from Tol, Wong, and Okabe & Ito, and worked through how ggsci, MetBrewer, The Economist, BBC News, and the UK Government Analysis Function set up their charts. Everything I learned went into a single style file.

SSCI-Plots is that file plus the helpers I kept reaching for. Coverage now extends past psychology into economics, public health, sociology, political science, education, business and management, geography, and methodology.

Install

Clone the repo into Claude Code's skills folder:

git clone https://github.com/O0000-code/SSCI-Plots.git ~/.claude/skills/ssci-plots

Claude Code picks the skill up automatically. When you ask for a publication-ready figure, the agent calls apply_style(...), get_palette(...), compose_grid(...), and so on. SKILL.md at the repo root tells the model when to use which helper.

Dependencies: matplotlib >= 3.5, numpy, pillow. The agent installs anything missing.

Want to call the library directly without Claude Code? See Use as a Python library below.

What's included

  • 12 journal presets with matching palettes — APA, Elsevier, Wiley, SAGE, Psychological Science, OUP / ASA, Nature, Science, NEJM, Lancet, BMJ, JAMA
  • 21 color-blind-safe categorical palettes — Tol, Okabe-Ito, IBM, ggsci, MetBrewer, Economist, BBC. Another 17 mood palettes ship for non-publication use, behind an explicit opt-in.
  • 3 diverging and 8 sequential colormaps — BuRd, PRGn, the viridis family, and ColorBrewer; all registered with matplotlib
  • 70+ matplotlib rcParams — APA 7 italics, custom mathtext, TrueType embedding, journal-specific panel labels
  • 27 helpers and a 55-chart catalog — see the API list below and references/ docs
  • 30 named figure sizes plus mode='slides' for posters and talks
27 helper functions — style · palettes · APA formatting · statistical annotations · multi-panel composition

Style entry points (3)

  • apply_style(journal=None, *, mode='paper') -- one call sets 70+ rcParams, registers colormaps, embeds TrueType fonts, and loads the matching palette when a journal is given
  • fig_size(width_cm, height_cm) -- converts cm to inches against journal column width
  • save_figure(fig, name) -- writes PDF, PNG, or both at the default DPI defined in ssci_style.py

Palette access (7)

  • get_palette(n, name='tol_bright', *, category=None, return_emphasis=False) -- n color-blind-safe categorical colors
  • get_grayscale(n) -- grayscale fallback for print
  • get_diverging_cmap(name='BuRd') -- diverging colormap for heatmaps
  • get_sequential_cmap(name='viridis') -- perceptually uniform sequential colormap (viridis family, ColorBrewer, Tailwind monochromatic)
  • list_palettes(category=None, publication_grade=None) -- list available palettes with metadata
  • get_emphasis_pair(focal=None, *, reference=...) -- one saturated color plus a neutral gray for treatment-vs-control comparisons (reference defaults to the gray set in ssci_style.py)
  • register_aesthetic_palette(name, *, acknowledge_non_publication_grade=True) -- opt-in switch for the 17 mood palettes

APA p-value and figure-text formatting (3)

  • format_p_value(p, style='apa') -- APA-formatted p (no leading zero, three decimals; 'stars' and 'exact' modes too)
  • p_to_stars(p) -- *** / ** / * / n.s.
  • format_apa_figure_text(figure_number, title, note_text=None, *, error_bar_type=None, model_fit=None) -- APA figure number / title / Note as Markdown, with optional structured note for error bars and SEM model fit

Statistical annotations (4)

  • add_significance_bracket(ax, x1, x2, y, p_value) -- bracket with automatic p-to-stars conversion
  • annotate_effect_size(ax, d, ci=None) -- effect size with optional CI
  • add_inline_stats(ax, items, position='top_left') -- inline block of test statistics, the kind seen in replication packages from major journals
  • add_reference_line(ax, value, orientation='horizontal') -- horizontal or vertical reference line with optional label

Axes, legend, panel labels (3)

  • remove_spines(ax) -- removes the top and right spines
  • setup_legend(ax, **kw) -- frameless legend in Title Case
  • add_panel_labels(axes, *, journal=None, prefix='', suffix='', overlay_bg=None) -- A / B / C panel labels in the case and size each journal expects, with per-journal overrides

Multi-panel composition (4)

  • compose_grid(layout, figsize='full_width', *, share=False, panel_labels='auto', ...) -- rectangular mosaic layouts ("ABC", "AB;CD", "AAB\nCDB"); raises SSCIPlotsMosaicError for non-rectangular shapes
  • small_multiples(n_rows, n_cols, *, share='all', panel_labels='auto', ...) -- N x M facet grid with shared axes by default
  • add_inset(ax, bbox=(0.55, 0.55, 0.4, 0.4), *, xlim=None, ylim=None, zoom_indicator=False) -- inset axes with an optional zoom rectangle and connector lines
  • compose_subfigures(n_rows, n_cols, *, height_ratios=None) -- stacked sub-figure regions for cases where each region needs its own colorbar or legend

Cross-panel helpers (3)

  • add_marginal_hist(ax, x, y, *, kind='hist'|'kde', size='20%') -- marginal histograms or KDEs along a scatter
  • add_shared_colorbar(fig, mappable, axes, *, location='right', shrink=0.7) -- one colorbar shared across several axes
  • add_shared_legend(fig, handles_or_axes, *, loc='lower center', ncol=None, region=None) -- deduplicated legend attached to the figure rather than to a single axes

Reference docs (loaded by Claude Code on demand):

Use as a Python library (optional)

The skill layer above only handles discovery for Claude Code. To call SSCI-Plots directly from a Jupyter notebook, script, or another tool:

git clone https://github.com/O0000-code/SSCI-Plots.git
cd SSCI-Plots
pip install matplotlib numpy pillow
from scripts.ssci_style import apply_style, get_palette, compose_grid, save_figure

apply_style(journal="lancet")                   # configures matplotlib + loads the Lancet palette
fig, axes = compose_grid("AB;CD", figsize="full_width")
# ... plot into axes['A'] / axes['B'] / axes['C'] / axes['D']
save_figure(fig, "fig_2")                       # writes fig_2.pdf and fig_2.png

See SKILL.md for the full helper API. A pip install package is on the roadmap.

A companion skill, deep-literature-search, is in progress and should land around the same time.

Contributing

This is a hobby project. Issue response is typically a week or two; PR review can be slower. Bug reports with a minimal reproduction are the most useful. See CONTRIBUTING.md.

License

MIT. See LICENSE.