Add P0 infrastructure for the Volve-DIA benchmark
Set up the data, parsing and quality-control layer for a public benchmark on the Volve daily drilling reports (DDR) and WITSML real-time data. - Data manifest with SHA-256 hashes of the three Volve subtrees in use. - DDR XML parser into DuckDB (1,759 reports, 26 wellbores, 23,447 activities, 17 tables) with locked expected counts. - Render QC of the publisher HTML against the XML (272,544 items). - OCR client for the shared chandra vLLM service, with a page cache keyed on model, prompt hash, dpi, max_tokens and temperature, and OCR QC against the HTML on a 26-report pilot. - Run logging (scripts/runlog.sh, logs/index.csv), the P0 runner and 40 tests. - Research plan, technical overview and progress page (in Vietnamese). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,227 @@
|
||||
# Color, Contrast, and Palette Selection
|
||||
|
||||
Reviewed 2026-10-01. Source IDs resolve in `sources.md`. A named “colorblind-safe” palette is not a guarantee that a rendered figure is accessible: background, line thickness, adjacency, text, category count, display/print conversion, and redundant encoding all matter.
|
||||
|
||||
## Start with data semantics
|
||||
|
||||
- **Qualitative:** unordered categories. Hue can separate groups; lightness should not imply an unintended ranking.
|
||||
- **Sequential:** ordered low-to-high values. Use monotonic perceived lightness.
|
||||
- **Diverging:** departure around a meaningful center. Use a neutral midpoint and document the normalization.
|
||||
- **Cyclic:** periodic values where endpoints meet.
|
||||
|
||||
Do not use a diverging map merely because values contain positive and negative numbers; the center must have scientific meaning. Do not use a rainbow map as a generic ordered scale. Paul Tol documents false visual transitions, lack of inherent magnitude ordering, and color-vision problems in ordinary rainbow schemes [TOL].
|
||||
|
||||
With Matplotlib, colormap and normalization are separate:
|
||||
|
||||
```python
|
||||
import matplotlib as mpl
|
||||
|
||||
norm = mpl.colors.TwoSlopeNorm(vmin=-2, vcenter=0, vmax=5)
|
||||
image = ax.imshow(values, cmap="RdBu_r", norm=norm)
|
||||
fig.colorbar(image, ax=ax, label="Change (unit)")
|
||||
```
|
||||
|
||||
Use `LogNorm` for strictly positive orders of magnitude, `SymLogNorm` for signed data with a disclosed linear zone, `BoundaryNorm` for meaningful classes, and `TwoSlopeNorm` for unequal ranges around a center [MPL-NORM].
|
||||
|
||||
## Okabe-Ito / Wong colors
|
||||
|
||||
The eight colors commonly reproduced from Wong’s Nature Methods article are [WONG]:
|
||||
|
||||
```python
|
||||
OKABE_ITO = [
|
||||
"#E69F00", # orange
|
||||
"#56B4E9", # sky blue
|
||||
"#009E73", # bluish green
|
||||
"#F0E442", # yellow
|
||||
"#0072B2", # blue
|
||||
"#D55E00", # vermillion
|
||||
"#CC79A7", # reddish purple
|
||||
"#000000", # black
|
||||
]
|
||||
```
|
||||
|
||||
Several light colors do not reach 3:1 against white. For thin lines or required graphical objects on white, start with the bundled five-color subset:
|
||||
|
||||
```python
|
||||
OKABE_ITO_ON_WHITE = [
|
||||
"#0072B2",
|
||||
"#D55E00",
|
||||
"#009E73",
|
||||
"#CC79A7",
|
||||
"#000000",
|
||||
]
|
||||
```
|
||||
|
||||
This subset is derived by WCAG sRGB contrast calculation; it is not a published palette or a compliance certification. Use marker/line-style redundancy and audit the actual rendering.
|
||||
|
||||
## Paul Tol qualitative schemes
|
||||
|
||||
Paul Tol’s canonical site moved to `sronpersonalpages.nl` in July 2026. The current technical note remains SRON/EPS/TN/09-002, issue 3.2, dated 2021-08-18 [TOL] [TOL-HOME].
|
||||
|
||||
The note states that the bright, high-contrast, vibrant, muted, and medium-contrast qualitative schemes are color-blind safe under its design/testing assumptions. It also states:
|
||||
|
||||
- high-contrast is the strongest choice for grayscale/monochrome separation;
|
||||
- medium-contrast provides three pairs but weaker grayscale separation;
|
||||
- light is reasonably distinct and intended mainly for labeled cell fills;
|
||||
- pale/dark are not sufficiently distinct for multi-series lines or maps and are meant for text backgrounds/foregrounds;
|
||||
- most multi-color qualitative schemes do not remain fully separable in grayscale.
|
||||
|
||||
Bundled fixed-order values:
|
||||
|
||||
```python
|
||||
TOL_BRIGHT = [
|
||||
"#4477AA", "#EE6677", "#228833", "#CCBB44",
|
||||
"#66CCEE", "#AA3377", "#BBBBBB",
|
||||
]
|
||||
|
||||
TOL_HIGH_CONTRAST = ["#004488", "#DDAA33", "#BB5566"]
|
||||
|
||||
TOL_VIBRANT = [
|
||||
"#EE7733", "#0077BB", "#33BBEE", "#EE3377",
|
||||
"#CC3311", "#009988", "#BBBBBB",
|
||||
]
|
||||
|
||||
TOL_MUTED = [
|
||||
"#CC6677", "#332288", "#DDCC77", "#117733", "#88CCEE",
|
||||
"#882255", "#44AA99", "#999933", "#AA4499",
|
||||
]
|
||||
|
||||
TOL_MEDIUM_CONTRAST = [
|
||||
"#6699CC", "#004488", "#EECC66",
|
||||
"#994455", "#997700", "#EE99AA",
|
||||
]
|
||||
```
|
||||
|
||||
The maximum intended series counts are 7, 3, 7, 9, and 6 respectively. Do not interpolate qualitative palettes.
|
||||
|
||||
## ColorBrewer
|
||||
|
||||
ColorBrewer 2.0 is an authoritative interactive resource for sequential, diverging, and qualitative cartographic schemes. It allows filtering by “colorblind safe,” “print friendly,” and “photocopy safe,” and exposes the supported number of data classes [COLORBREWER].
|
||||
|
||||
Use the exact class count shown by ColorBrewer. A scheme marked safe at one class count may not be marked safe at another. ColorBrewer’s flags are design guidance for its intended mapping context, not a WCAG conformance result for arbitrary line widths, backgrounds, or text.
|
||||
|
||||
Matplotlib exposes many ColorBrewer-derived maps. Verify the exact map direction and class count rather than relying on its name.
|
||||
|
||||
## Perceptually uniform continuous maps
|
||||
|
||||
Matplotlib recommends selecting maps based on data semantics and discusses lightness behavior in its colormap guide [MPL-CMAP]. Common continuous candidates:
|
||||
|
||||
- `viridis`, `plasma`, `inferno`, `magma`: perceptually uniform sequential families;
|
||||
- `cividis`: designed with color-vision deficiencies in mind;
|
||||
- `RdBu_r`, `PuOr`, `BrBG`: possible diverging candidates after checking the center, direction, contrast, and grayscale behavior.
|
||||
|
||||
No list is universally safe. A map can be perceptually uniform yet still fail to distinguish a narrow feature at the chosen size, or lose detail during RGB-to-CMYK conversion.
|
||||
|
||||
## WCAG contrast: what to test
|
||||
|
||||
WCAG 2.2 is normative for web content [WCAG22]:
|
||||
|
||||
- normal text: 4.5:1 against its background (SC 1.4.3 AA);
|
||||
- large text: 3:1 (SC 1.4.3 AA);
|
||||
- graphical objects required to understand content: 3:1 against adjacent colors (SC 1.4.11 AA);
|
||||
- color must not be the only visual means of conveying information (SC 1.4.1 A).
|
||||
|
||||
W3C’s understanding document uses line and pie charts as examples and explains that required graphical objects are tested against adjacent colors; all data-series colors do not automatically need 3:1 against each other when they do not overlap [WCAG-NONTEXT].
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
uv run --isolated --no-project --python 3.13 \
|
||||
python scripts/palette_audit.py \
|
||||
--palette okabe_ito_on_white \
|
||||
--background FFFFFF \
|
||||
--role graphical
|
||||
```
|
||||
|
||||
The CLI reports:
|
||||
|
||||
- exact WCAG sRGB contrast against the chosen background;
|
||||
- pairwise contrast;
|
||||
- pairwise CIE L* separation after removing hue.
|
||||
|
||||
Its default grayscale threshold (ΔL* 10) is a heuristic. It is not a WCAG threshold and does not simulate every color-vision deficiency, printer, profile, or viewing condition.
|
||||
|
||||
## Redundant encoding
|
||||
|
||||
Use at least one non-color cue:
|
||||
|
||||
```python
|
||||
colors = ["#0072B2", "#D55E00", "#009E73"]
|
||||
linestyles = ["-", "--", "-."]
|
||||
markers = ["o", "s", "^"]
|
||||
|
||||
for index, series in enumerate(series_list):
|
||||
ax.plot(
|
||||
x,
|
||||
series,
|
||||
color=colors[index],
|
||||
linestyle=linestyles[index],
|
||||
marker=markers[index],
|
||||
markevery=5,
|
||||
label=labels[index],
|
||||
)
|
||||
```
|
||||
|
||||
For bars, use edge contrast, labels, and restrained hatching. For images, consider accessible channel combinations plus separate grayscale panels. Direct labels often outperform distant legends.
|
||||
|
||||
## Missing and out-of-range colors
|
||||
|
||||
Assign explicit colors to missing and out-of-range values:
|
||||
|
||||
```python
|
||||
import matplotlib as mpl
|
||||
|
||||
cmap = mpl.colormaps["viridis"].with_extremes(
|
||||
bad="#777777",
|
||||
under="#222222",
|
||||
over="#FDE725",
|
||||
)
|
||||
```
|
||||
|
||||
Label these states in the colorbar/legend. Never let missing values default to the low end of a quantitative scale.
|
||||
|
||||
## Seaborn and Plotly
|
||||
|
||||
Seaborn 0.13.2 accepts palette names, lists, and dictionaries through `palette=`/`set_palette()`. Apply a Matplotlib style before Seaborn only if the subsequent `sns.set_theme()` call will not overwrite the intended rc settings; pass `rc=` explicitly when needed [SEABORN-PALETTE] [SEABORN-THEME].
|
||||
|
||||
```python
|
||||
import seaborn as sns
|
||||
|
||||
sns.set_theme(style="ticks", context="paper")
|
||||
sns.set_palette(OKABE_ITO_ON_WHITE)
|
||||
```
|
||||
|
||||
For Plotly, set categorical colors explicitly and add symbols/dashes:
|
||||
|
||||
```python
|
||||
fig = px.scatter(
|
||||
frame,
|
||||
x="x",
|
||||
y="y",
|
||||
color="group",
|
||||
symbol="group",
|
||||
color_discrete_sequence=OKABE_ITO_ON_WHITE,
|
||||
)
|
||||
```
|
||||
|
||||
Check the static export too. Interactive hover does not replace contrast, labels, keyboard operation, alt text, or a static fallback.
|
||||
|
||||
## Color management
|
||||
|
||||
- Work in sRGB unless the publisher or calibrated workflow requires another space.
|
||||
- Preserve ICC profiles in scientific raster images when relevant.
|
||||
- Preview print conversion when the publisher converts RGB to CMYK.
|
||||
- Do not alter raw intensity data merely to obtain attractive colors.
|
||||
- Record channel mappings, color limits, normalization, and any color-space conversion.
|
||||
- Avoid transparency when blending with an unknown background can change contrast.
|
||||
|
||||
## Review checklist
|
||||
|
||||
- [ ] Palette type matches data semantics.
|
||||
- [ ] Center, limits, normalization, and missing-value color are explicit.
|
||||
- [ ] Foreground/background contrast was audited at final size.
|
||||
- [ ] Color is redundant with shape, line style, hatching, labels, or layout.
|
||||
- [ ] Grayscale was inspected without treating it as a complete accessibility test.
|
||||
- [ ] Print/profile conversion was reviewed when relevant.
|
||||
- [ ] Palette and category mapping are consistent across figures.
|
||||
- [ ] Underlying values and an accessible text/table alternative are available.
|
||||
@@ -0,0 +1,170 @@
|
||||
# Publisher and Journal Figure Snapshots
|
||||
|
||||
Reviewed 2026-10-01 against official pages, except the explicitly historical Science snapshot below. Requirements are date-sensitive and often depend on the journal, article type, figure type, and submission phase. Verify the live target-journal page before submission. Source IDs resolve in `sources.md`.
|
||||
|
||||
The machine-readable subset in `assets/publisher_profiles.json` is for planning and deterministic screening only. `scripts/export_plan.py` never claims compliance.
|
||||
|
||||
## Nature (flagship journal)
|
||||
|
||||
**Scope:** `Nature` final submission after acceptance in principle, not all Nature Portfolio journals [NATURE-FINAL] [NATURE-FIG].
|
||||
|
||||
- Standard widths: 89 mm single column, 183 mm double column; 120-136 mm is possible for one-and-a-half columns.
|
||||
- Full page depth: 247 mm.
|
||||
- Panels: lowercase bold upright `a`, `b`, `c`, 8 pt.
|
||||
- Other text: 5-7 pt at final size; Helvetica or Arial preferred.
|
||||
- Keep text and line art editable; do not outline or rasterize them.
|
||||
- Preferred line/graph containers include AI, PostScript, vector EPS, and PDF.
|
||||
- Preferred raster source: layered PSD or TIFF. The final-submission page states 300-600 dpi for photographs; minimum 300 dpi at maximum use size.
|
||||
- The newer research-figure guide recommends export images at 450 dpi or above because online proofs top out at 450 dpi. This is a recommendation layered on the final-submission minimum, not a universal 450 dpi rule.
|
||||
- RGB is recommended; final print conversion may use CMYK.
|
||||
- Type 42 fonts are requested. The figure guide explicitly gives `matplotlib.rcParams["pdf.fonttype"] = 42`.
|
||||
- High-quality JPEG can be accepted when it is the only option for a photograph. Therefore, “Nature never accepts JPEG” is false.
|
||||
- Extended Data has different rules: RGB, maximum 300 ppi, maximum 10 MB, and JPEG preferred with TIFF/EPS alternatives.
|
||||
|
||||
Do not apply these flagship rules automatically to Nature Communications, Scientific Reports, npj journals, or Nature Reviews; each has its own page.
|
||||
|
||||
## Science (AAAS flagship journal)
|
||||
|
||||
**Scope:** historical `Science` snapshot accessed 2026-07-23, with separate initial and revised stages [SCIENCE-INITIAL] [SCIENCE-REVISED]. Both pages blocked direct and fresh extraction on 2026-10-01. The numbers below remain provisional until live instructions are checked.
|
||||
|
||||
### Initial submission
|
||||
|
||||
- A single manuscript file with embedded figures is preferred.
|
||||
- Figures should be 300 dpi for review.
|
||||
- Printed widths are usually 5.7 cm (one column), 12.1 cm (two columns), or 18.4 cm (three columns).
|
||||
- Vector creation is preferred.
|
||||
- Use sans serif, preferably Helvetica. Lettering should be about 7 pt after reduction and no smaller than 5 pt.
|
||||
- Avoid red/green combinations and similar hues as sole identifiers; add shape/texture where needed.
|
||||
- Scales should not extend beyond the plotted data merely as empty range.
|
||||
|
||||
### Revised manuscript
|
||||
|
||||
- Upload each figure separately.
|
||||
- Preferred vector formats: PDF, EPS, or AI.
|
||||
- Raster illustrations/diagrams and photographs/microscopy: TIFF.
|
||||
- Vector/raster combinations: PDF or EPS.
|
||||
- Line art without a vector original: at least 300 dpi at final size, preferably higher.
|
||||
- Color and grayscale images: at least 300 dpi at final size.
|
||||
- Upsampling is not permitted.
|
||||
- PowerPoint and figures embedded in Word are not accepted at this stage.
|
||||
|
||||
The 2026-07-23 snapshot did **not** state the older blanket “1,000 dpi line art / 600 dpi combination” numbers that this skill previously claimed.
|
||||
|
||||
Science Advances and other AAAS journals publish separate figure guides; do not reuse the flagship profile without checking.
|
||||
|
||||
## Cell Press
|
||||
|
||||
**Scope:** general Cell Press figure page; exceptions are explicitly listed for STAR Protocols and `Cell` Leading Edge [CELL-FIG].
|
||||
|
||||
### Initial submission and review
|
||||
|
||||
- Cell Press accepts a wide range of formats, sizes, and resolutions.
|
||||
- Figures may be embedded or uploaded separately.
|
||||
- Individual 1-2 MB files are recommended for reviewer convenience.
|
||||
|
||||
### Final production
|
||||
|
||||
- Upload each main figure as one separate file containing all its panels; keep titles/legends in the manuscript.
|
||||
- Recommended overall maximum: 16.5 × 20 cm. This is framed as a recommendation.
|
||||
- Two-column article widths: 8.5 cm, 11.4 cm, and 17.4 cm.
|
||||
- Three-column formats: 5.5 cm, 11.4 cm, and 17.4 cm.
|
||||
- Maximum individual file size: 20 MB.
|
||||
- TIFF and PDF are preferred for most journals/types. EPS, JPEG, and CDX are accepted. Special cases differ.
|
||||
- Color/grayscale: at least 300 dpi; black-and-white: at least 500 dpi; line art: at least 1,000 dpi at final size.
|
||||
- RGB, Arial, capital panel letters, 6-8 pt text, and 0.5-1.5 pt strokes.
|
||||
- Embed fonts. General production guidance says flatten layers, except specified `Cell` Leading Edge material.
|
||||
- Do not use red and green together as the only distinction.
|
||||
|
||||
Cell Press requires minimal image processing, original unprocessed data on request, and disclosure of processing/stitching. Its current policy prohibits generative AI/AI-assisted alteration of research/data images, including brightness, contrast, or color-balance adjustment performed by such tools.
|
||||
|
||||
## PLOS research journals
|
||||
|
||||
**Scope:** current PLOS Computational Biology page, consistent with the sampled PLOS research-journal figure pages [PLOS-FIG]. Verify the selected PLOS journal.
|
||||
|
||||
- Formatting requirements are waived until provisional Editorial Accept.
|
||||
- Final figure format: TIFF or EPS.
|
||||
- Width: 789-2250 px at 300 dpi, equivalent to 6.68-19.05 cm.
|
||||
- Text-column alignment recommendation: no wider than 13.2 cm.
|
||||
- Maximum height: 2625 px at 300 dpi, equivalent to 22.23 cm.
|
||||
- Resolution: 300-600 dpi at final dimensions. The page warns that above 600 may trigger resizing and below 300 will degrade output.
|
||||
- The summary table says less than 10 MB; the detailed section says 10 MB or less. The planner conservatively uses the stricter boundary and flags the inconsistency.
|
||||
- Text: Arial, Times, or Symbol, 8-12 pt.
|
||||
- Color mode: RGB 8-bit/channel or grayscale.
|
||||
- Put all panels of one figure in one single-page file. TIFF must have no alpha channel and must use LZW compression.
|
||||
- The pixel bounds are expressed at 300 dpi: a 600 dpi raster at the same physical size contains twice as many pixels per axis. The screen compares physical size via its 300 dpi equivalent, not an absolute 2250-pixel cap.
|
||||
- Captions remain in the manuscript; filenames are `Fig1.tif`, `Fig2.eps`, and so on.
|
||||
- Do not increase pixel count and present that as improved resolution.
|
||||
|
||||
For manuscripts submitted on or after 2026-04-01, original uncropped, minimally adjusted blot/gel images must be supplied before acceptance. Adjustments must not alter scientific information and must be applied consistently.
|
||||
|
||||
## Elsevier
|
||||
|
||||
**Scope:** publisher-general artwork instructions. Elsevier explicitly says journal-specific Guides for Authors can override them [ELSEVIER-FORMAT] [ELSEVIER-SIZE].
|
||||
|
||||
- Recommended containers: TIFF for halftones/bitmaps, EPS for vector-based images (including embedded images), and PDF for vector/text material.
|
||||
- JPEG and Microsoft Office files are accepted in the general checklist; use the journal page to decide suitability.
|
||||
- RGB is preferred unless the journal says otherwise.
|
||||
- General target widths: 90 mm single, 140 mm one-and-a-half, 190 mm full; 30 mm is the listed minimal size.
|
||||
- General raster targets at final size: 300 dpi halftone, 500 dpi combination, 1,000 dpi line art.
|
||||
- General lettering rule of thumb: 7 pt normal text, not smaller than 6 pt for sub/superscripts.
|
||||
|
||||
These are publisher defaults, not universal Elsevier-journal hard limits.
|
||||
|
||||
## IEEE journals
|
||||
|
||||
**Scope:** IEEE Author Center journal graphics page, modified 2025-02-25 [IEEE-SIZE].
|
||||
|
||||
- Acceptable vector formats listed on the page: PS, EPS, PDF.
|
||||
- Non-vector color/grayscale graphics: **greater than** 300 dpi.
|
||||
- Black-and-white line art: **greater than** 600 dpi.
|
||||
- One-column width: 3.5 in / 88.9 mm.
|
||||
- Two-column width: 7.16 in / 182 mm.
|
||||
- IEEE warns that increasing resolution after creation does not improve quality.
|
||||
|
||||
Conference and magazine instructions can differ; use their separate Author Center pages.
|
||||
|
||||
## BMC
|
||||
|
||||
**Scope:** BMC Bioinformatics, used as a current BMC-journal example rather than a guaranteed BMC-wide profile [BMC-BIOINFO].
|
||||
|
||||
- Web widths: 600 px standard, 1200 px high resolution.
|
||||
- PDF widths: 85 mm half page, 170 mm full page.
|
||||
- Maximum figure-plus-legend height: 225 mm.
|
||||
- Approximately 300 dpi at final size.
|
||||
- Fonts embedded; lines wider than 0.25 pt at final width.
|
||||
- Accepted formats include EPS, PDF, Word, PowerPoint, TIFF, JPEG, PNG, BMP, and CDX; JPEG is described as less suitable for graphical images.
|
||||
- One composite file per multi-panel figure; individual file maximum 10 MB.
|
||||
|
||||
BMC Bioinformatics now redirects to Springer Nature Link. The approximate DPI target has no numeric tolerance and the height includes the legend; the planner reports these as review items rather than unconditional passes.
|
||||
|
||||
## ACS Publications
|
||||
|
||||
**Scope:** legacy “Preparing Manuscript Graphics,” currently hosted on the official ACS Paragon Plus site with an explicit update date of 2006-01-21 [ACS-GRAPHICS]. It is not a current universal digital-export profile; use the selected journal’s Author Guidelines.
|
||||
|
||||
- Listed maximum dimensions: 3.25 in single column, 7 in double column, 9.5 in length.
|
||||
- Lettering should be no smaller than 5 pt after reduction; Helvetica/Arial are suggested.
|
||||
- Lines should be no thinner than 1 pt on that general page.
|
||||
- The page mentions using the best available resolution and 600+ dpi printing, but it does not establish a universal per-figure digital file-format/DPI rule for all ACS journals.
|
||||
|
||||
Use the selected ACS journal’s current Author Guidelines for formats, color, resolution, and TOC/abstract graphics. The planner intentionally does not invent missing ACS-wide requirements.
|
||||
|
||||
## Rules that are not universal
|
||||
|
||||
Do not present these as cross-publisher laws:
|
||||
|
||||
- “JPEG is never accepted.” Several publishers accept it for photographs or specific workflows.
|
||||
- “All line art must be 1,000/1,200 dpi.” Vector output is often preferred, and current Science revised guidance says at least 300 dpi when vector is unavailable.
|
||||
- “All publishers require grayscale compatibility.” Accessibility guidance varies; use redundant encoding regardless.
|
||||
- “All figures must be RGB.” RGB is often preferred, but Nature accepts RGB or CMYK for final print artwork and target-journal rules can differ.
|
||||
- “All figures need error bars/significance stars.” The right display depends on the estimand, data, and analysis.
|
||||
- “A matching DPI/width means compliant.” Technical metadata is only one part of submission review.
|
||||
|
||||
## Submission-stage workflow
|
||||
|
||||
1. Identify exact journal, article type, figure type, and current stage.
|
||||
2. Save the live official page URL and access date.
|
||||
3. Create a plan with `scripts/export_plan.py`.
|
||||
4. Export with explicit dimensions and settings.
|
||||
5. Inspect the delivered file with `scripts/image_metadata.py`.
|
||||
6. Review fonts, embedded rasters, image integrity, accessibility, caption, and source data manually.
|
||||
7. Re-check official instructions immediately before upload.
|
||||
@@ -0,0 +1,356 @@
|
||||
# Current Matplotlib, Seaborn, and Plotly Patterns
|
||||
|
||||
Verified 2026-10-01 against Matplotlib 3.11.2, Seaborn 0.13.2, Plotly 7.1.0, Kaleido 1.4.0, Pillow 12.3.0, and pypdf 6.19.0. Source IDs resolve in `sources.md`.
|
||||
|
||||
Run examples from the skill directory with pinned direct dependencies:
|
||||
|
||||
```bash
|
||||
uv run --isolated --no-project --python 3.13 \
|
||||
--with "matplotlib==3.11.2" \
|
||||
--with "seaborn==0.13.2" \
|
||||
--with "plotly==7.1.0" \
|
||||
--with "kaleido==1.4.0" \
|
||||
--with "pillow==12.3.0" \
|
||||
--with "pypdf==6.19.0" \
|
||||
python your_figure.py
|
||||
```
|
||||
|
||||
These pins are a dated direct-dependency snapshot, not a lock of all transitive artifacts. Keep a lock in the consuming project for exact replay. The snippets share imports/variables: supply your scientific `frame`, `x`, and `y`. They were exercised with synthetic fixtures; they do not validate an analysis of your data.
|
||||
|
||||
Start `your_figure.py` with this bootstrap when running from the skill directory:
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
skill_root = Path.cwd()
|
||||
sys.path[:0] = [str(skill_root / "scripts"), str(skill_root / "assets")]
|
||||
Path("outputs").mkdir(exist_ok=True)
|
||||
```
|
||||
|
||||
## Rendering and hardcopy backends
|
||||
|
||||
Matplotlib separates interactive display backends from hardcopy renderers. The current built-ins include PDF (`pdf`), PS (`ps`, `eps`), SVG (`svg`), PGF (`pgf`, `pdf` through TeX), and optional Cairo (`png`, `ps`, `pdf`, `svg`); Agg is the common raster renderer [MPL-BACKENDS]. JPEG, TIFF, and WebP saving uses Pillow through the raster path.
|
||||
|
||||
Available output depends on the active backend/build:
|
||||
|
||||
```python
|
||||
supported = fig.canvas.get_supported_filetypes()
|
||||
print(supported)
|
||||
```
|
||||
|
||||
`Figure.savefig(..., backend="cairo")` or `backend="pgf"` can select another renderer, but Matplotlib documents the default as normally sufficient [MPL-SAVE]. PGF requires a working TeX setup; Cairo requires pycairo or cairocffi. Inspect output because a vector container can still contain rasterized artists.
|
||||
|
||||
## Scoped style and exact dimensions
|
||||
|
||||
Prefer temporary style contexts to global state:
|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
from style_presets import style_context
|
||||
|
||||
with style_context("default", palette_name="okabe_ito_on_white"):
|
||||
fig, ax = plt.subplots(
|
||||
figsize=(89 / 25.4, 60 / 25.4),
|
||||
layout="constrained",
|
||||
)
|
||||
ax.plot([0, 1, 2], [1, 3, 2], marker="o", label="Observed")
|
||||
ax.set(xlabel="Time (hours)", ylabel="Response (unit)")
|
||||
ax.legend()
|
||||
```
|
||||
|
||||
`layout="constrained"` handles labels, legends, nested layouts, and colorbars more flexibly than `tight_layout`; calling `tight_layout()` turns constrained layout off [MPL-LAYOUT].
|
||||
|
||||
If exact page dimensions matter, do not export with `bbox_inches="tight"`; it recalculates the bounding box and changes the physical output size [MPL-SAVE].
|
||||
|
||||
You can also use the bundled parseable style:
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
skill_root = Path(".") # run from the skill directory
|
||||
with plt.style.context(skill_root / "assets" / "publication.mplstyle"):
|
||||
fig, ax = plt.subplots(layout="constrained")
|
||||
```
|
||||
|
||||
## Preserve raw observations and define uncertainty
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
rng = np.random.default_rng(20260723)
|
||||
groups = {
|
||||
"Control": rng.normal(0.0, 1.0, 24),
|
||||
"Treatment": rng.normal(0.7, 1.1, 24),
|
||||
}
|
||||
|
||||
fig, ax = plt.subplots(figsize=(3.5, 2.8), layout="constrained")
|
||||
for position, (label, values) in enumerate(groups.items()):
|
||||
jitter = rng.uniform(-0.08, 0.08, len(values))
|
||||
ax.scatter(
|
||||
position + jitter,
|
||||
values,
|
||||
alpha=0.65,
|
||||
label=label,
|
||||
)
|
||||
mean = values.mean()
|
||||
sem = values.std(ddof=1) / np.sqrt(len(values))
|
||||
ax.errorbar(position, mean, yerr=sem, color="black", capsize=3)
|
||||
|
||||
ax.set(
|
||||
xticks=range(len(groups)),
|
||||
xticklabels=list(groups),
|
||||
ylabel="Response (unit)",
|
||||
)
|
||||
```
|
||||
|
||||
Caption the error bars as mean ± one SEM and state `n=24` independent observations per group. If independence is false, use an analysis and interval that respects the design.
|
||||
|
||||
## Missing data and no silent interpolation
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
time = np.arange(8)
|
||||
signal = np.array([1.0, 1.4, np.nan, np.nan, 2.1, 2.0, 2.4, 2.7])
|
||||
|
||||
fig, ax = plt.subplots(layout="constrained")
|
||||
ax.plot(time, signal, marker="o", label="Observed") # gaps remain gaps
|
||||
ax.scatter(
|
||||
[2, 3], [0.04, 0.04], transform=ax.get_xaxis_transform(),
|
||||
marker="x", color="0.35", label="Missing (axis strip)",
|
||||
)
|
||||
ax.set(xlabel="Time (days)", ylabel="Signal (unit)")
|
||||
ax.legend()
|
||||
```
|
||||
|
||||
If a model estimates the missing interval, plot the model separately with its uncertainty and identify it as modeled, not observed.
|
||||
|
||||
## Log axes and explicit nonpositive policy
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
concentration = np.array([0.1, 1.0, 10.0, 100.0])
|
||||
response = np.array([0.4, 0.9, 2.1, 4.3])
|
||||
|
||||
fig, ax = plt.subplots(layout="constrained")
|
||||
ax.plot(concentration, response, marker="o")
|
||||
ax.set_xscale("log", base=10)
|
||||
ax.set(xlabel="Concentration (µM; log10 axis)", ylabel="Response (unit)")
|
||||
```
|
||||
|
||||
Do not silently omit zeros or negatives. State the measurement-domain rule or use another representation.
|
||||
|
||||
## Centered heatmap and missing-value color
|
||||
|
||||
```python
|
||||
import matplotlib as mpl
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
values = np.array([
|
||||
[-2.0, -0.5, 0.1],
|
||||
[-1.1, np.nan, 1.8],
|
||||
[-0.2, 0.7, 3.0],
|
||||
])
|
||||
norm = mpl.colors.TwoSlopeNorm(vmin=-2, vcenter=0, vmax=3)
|
||||
cmap = mpl.colormaps["RdBu_r"].with_extremes(bad="#777777")
|
||||
|
||||
fig, ax = plt.subplots(layout="constrained")
|
||||
image = ax.imshow(values, norm=norm, cmap=cmap, interpolation="nearest")
|
||||
colorbar = fig.colorbar(image, ax=ax)
|
||||
colorbar.set_label("Change from baseline (unit)")
|
||||
ax.set(xlabel="Sample", ylabel="Feature")
|
||||
```
|
||||
|
||||
`TwoSlopeNorm` gives each side of the center a different linear mapping. Use `CenteredNorm` when symmetric treatment around a center is appropriate, `LogNorm` for strictly positive orders of magnitude, and `BoundaryNorm` for declared classes [MPL-NORM].
|
||||
|
||||
## Multi-panel layout
|
||||
|
||||
```python
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
fig = plt.figure(figsize=(7.0, 4.0), layout="constrained")
|
||||
subfigures = fig.subfigures(1, 2, width_ratios=[2, 1])
|
||||
left_axes = subfigures[0].subplots(2, 1, sharex=True)
|
||||
right_ax = subfigures[1].subplots()
|
||||
|
||||
for label, ax in zip("ABC", [*left_axes, right_ax]):
|
||||
ax.text(
|
||||
-0.12,
|
||||
1.05,
|
||||
label,
|
||||
transform=ax.transAxes,
|
||||
fontweight="bold",
|
||||
va="top",
|
||||
)
|
||||
```
|
||||
|
||||
`GridSpec`, subgrids, `subplot_mosaic`, and subfigures all work with constrained layout [MPL-LAYOUT] [MPL-GRIDSPEC].
|
||||
|
||||
## Selective rasterization in vector output
|
||||
|
||||
Dense point clouds can make PDF/SVG huge. Rasterize only the dense artist:
|
||||
|
||||
```python
|
||||
fig, ax = plt.subplots(layout="constrained")
|
||||
ax.scatter(x, y, s=2, alpha=0.25, rasterized=True)
|
||||
ax.set(xlabel="Predictor (unit)", ylabel="Outcome (unit)")
|
||||
|
||||
from figure_export import export_figure
|
||||
|
||||
report = export_figure(
|
||||
fig,
|
||||
"outputs/figure1",
|
||||
formats=["pdf", "png"],
|
||||
dpi=600, # controls PNG and rasterized artists embedded in PDF
|
||||
provenance={
|
||||
"raw_data": "data/observations.csv",
|
||||
"transformations": ["rows filtered by predeclared QC flag"],
|
||||
"uncertainty": "none displayed",
|
||||
"missing_data": "retained as gaps",
|
||||
},
|
||||
write_manifest=True,
|
||||
)
|
||||
```
|
||||
|
||||
The exporter:
|
||||
|
||||
- refuses implicit overwrite;
|
||||
- preserves page dimensions by default;
|
||||
- passes DPI to vector backends for embedded raster artists;
|
||||
- writes TIFF with LZW compression;
|
||||
- can keep TrueType text editable in PDF/PS;
|
||||
- can write an explicit provenance manifest.
|
||||
|
||||
It does not inspect data truth or certify submission compliance.
|
||||
|
||||
## Raster image export and inspection
|
||||
|
||||
```python
|
||||
report = export_figure(
|
||||
fig,
|
||||
"outputs/microscopy_panel",
|
||||
formats=["tiff"],
|
||||
tiff_rgb=True, # remove alpha only after verifying every rendered pixel is opaque
|
||||
dpi=300,
|
||||
facecolor="white",
|
||||
overwrite=False,
|
||||
)
|
||||
```
|
||||
|
||||
Then inspect:
|
||||
|
||||
```bash
|
||||
uv run --isolated --no-project --python 3.13 \
|
||||
--with "pillow==12.3.0" \
|
||||
python scripts/image_metadata.py outputs/microscopy_panel.tiff \
|
||||
--format tiff --mode RGB --min-dpi 300 --target-width-mm 85 \
|
||||
--alpha-policy forbid
|
||||
```
|
||||
|
||||
Effective DPI is pixel width divided by final width in inches. Changing only the TIFF DPI tag does not create detail.
|
||||
|
||||
## Seaborn 0.13.2
|
||||
|
||||
Seaborn remains built on Matplotlib. Use axes-level functions for custom multi-panel layouts and figure-level functions for automatic faceting [SEABORN-FAQ].
|
||||
|
||||
```python
|
||||
import seaborn as sns
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
from color_palettes import OKABE_ITO_ON_WHITE
|
||||
from style_presets import style_context
|
||||
|
||||
sns.set_theme(style="ticks", context="paper", palette=OKABE_ITO_ON_WHITE)
|
||||
with style_context("default", palette_name="okabe_ito_on_white"):
|
||||
fig, ax = plt.subplots(figsize=(3.5, 2.8), layout="constrained")
|
||||
sns.lineplot(
|
||||
data=frame,
|
||||
x="time",
|
||||
y="response",
|
||||
hue="treatment",
|
||||
style="treatment",
|
||||
markers=True,
|
||||
errorbar=("ci", 95),
|
||||
n_boot=5000,
|
||||
seed=20260723,
|
||||
ax=ax,
|
||||
)
|
||||
ax.set(xlabel="Time (hours)", ylabel="Response (unit)")
|
||||
```
|
||||
|
||||
Seaborn line plots can drop rows with missing values and join the remaining points. Use the explicit Matplotlib gap example above when gaps carry scientific meaning.
|
||||
|
||||
Current `errorbar` choices include `"sd"`, `"se"`, `"pi"`, `"ci"`, tuples, callables, or `None`. The old `ci=` interface is not the current general API [SEABORN-ERROR].
|
||||
|
||||
For categorical axes whose numeric/datetime values must retain their real spacing, use supported functions with `native_scale=True`. Do not assume every categorical plot uses native coordinates by default.
|
||||
|
||||
## Plotly 7.1 and Kaleido 1.4
|
||||
|
||||
Interactive HTML (the supplied `fig` here is a Plotly figure):
|
||||
|
||||
```python
|
||||
fig.write_html(
|
||||
"outputs/exploration.html",
|
||||
include_plotlyjs=True, # self-contained, larger file
|
||||
full_html=True,
|
||||
config={"modeBarButtonsToRemove": ["shareChart"]},
|
||||
)
|
||||
```
|
||||
|
||||
Static image:
|
||||
|
||||
```python
|
||||
fig.write_image(
|
||||
"outputs/figure.svg",
|
||||
width=700,
|
||||
height=450,
|
||||
scale=1,
|
||||
)
|
||||
```
|
||||
|
||||
Batch export is faster with Kaleido v1:
|
||||
|
||||
```python
|
||||
import plotly.io as pio
|
||||
|
||||
pio.write_images(
|
||||
fig=[figure_a, figure_b],
|
||||
file=["outputs/a.pdf", "outputs/b.pdf"],
|
||||
)
|
||||
```
|
||||
|
||||
Current facts [PLOTLY-STATIC] [PLOTLY-7] [KALEIDO]:
|
||||
|
||||
- Kaleido v1 requires a compatible Chrome/Chromium installation; Chrome is no longer bundled.
|
||||
- Plotly `write_image` supports PNG, JPEG, WebP, SVG, and PDF.
|
||||
- EPS was supported only by Kaleido versions earlier than 1.0.
|
||||
- `engine=` and Orca are removed in Plotly 7. Kaleido <1 is unsupported.
|
||||
- `plotly.io.kaleido.scope` is removed; use `plotly.io.defaults`. MathJax must be version 3 or 4.
|
||||
- Width/height are logical pixels and `scale` multiplies output pixels; `scale=3` is **not inherently “300 DPI.”**
|
||||
- WebGL traces embed raster content inside vector exports.
|
||||
- Fully offline MathJax/topojson use requires local resources; do not assume a network-independent export when a figure references external assets.
|
||||
|
||||
Plotly 7 adds a Share Chart modebar button; remove it when a local deliverable should not offer upload/sharing. Embedding Plotly.js does not package externally referenced tiles, images, MathJax, or topojson.
|
||||
|
||||
An interactive HTML file does not replace a static fallback, caption, alt text, keyboard review, or accessible data table.
|
||||
|
||||
## Font and transparency checks
|
||||
|
||||
Matplotlib 3.11.2 defaults PDF/PS to Type 3 and SVG text to paths. The bundled presets instead use PDF/PS Type 42 and leave SVG text as text [MPL-STYLE]. Verify the actual PDF:
|
||||
|
||||
```bash
|
||||
uv run --isolated --no-project --python 3.13 \
|
||||
--with "pypdf==6.19.0" \
|
||||
python scripts/image_metadata.py outputs/figure1.pdf
|
||||
```
|
||||
|
||||
SVG text is not an embedded font; its appearance depends on the renderer’s installed fonts. If portability matters more than editable/searchable text, use paths and retain an editable source separately.
|
||||
|
||||
Use opaque white submission output unless transparency is explicitly required. Transparent artists blend with the destination and can change apparent contrast [MPL-SAVE].
|
||||
@@ -0,0 +1,196 @@
|
||||
# Publication Figure Principles
|
||||
|
||||
Reviewed 2026-10-01. These are general scientific-communication principles, not publisher requirements. Date-sensitive rules belong in `journal_requirements.md`. Source IDs resolve in `sources.md`.
|
||||
|
||||
## Preserve evidence before styling
|
||||
|
||||
Keep three layers separate:
|
||||
|
||||
1. **Raw/source data**: immutable originals, acquisition metadata, exclusions, and missing-value codes.
|
||||
2. **Transformation record**: executable code or a machine-readable log of filtering, normalization, aggregation, statistical estimation, image processing, and random seeds.
|
||||
3. **Presentation output**: the figure and an export manifest recording dimensions, format, package versions, and source references.
|
||||
|
||||
Do not overwrite raw images or tabular data. Keep native-resolution images. Upsampling changes pixel count, not information; PLOS, Science, Nature, Cell Press, Elsevier, and IEEE explicitly warn against treating it as improved quality [PLOS-FIG] [SCIENCE-REVISED] [NATURE-FINAL] [CELL-FIG] [ELSEVIER-SIZE] [IEEE-SIZE].
|
||||
|
||||
For experimental/observational images:
|
||||
|
||||
- Apply necessary brightness, contrast, and color adjustments consistently to the whole image unless a disclosed scientific method requires otherwise.
|
||||
- Never selectively erase, obscure, clone, or enhance features.
|
||||
- Preserve background and nonspecific signal.
|
||||
- Mark and explain splices, omitted lanes, composites, or stitched fields.
|
||||
- Retain originals and the exact processing steps. Some publishers request originals during review or production [CELL-FIG] [PLOS-FIG].
|
||||
|
||||
The bundled exporter can write a provenance manifest, but it cannot confirm that supplied provenance is complete.
|
||||
|
||||
## Avoid visual deception
|
||||
|
||||
### Baselines and context
|
||||
|
||||
- **Bars and filled areas encode length/area from a baseline**: normally show the zero baseline. If a nonzero reference is scientifically meaningful, make that reference explicit and avoid implying absolute magnitude.
|
||||
- **Points and lines encode position**: a nonzero axis limit can be valid, but show enough context, disclose breaks, and avoid choosing limits solely to magnify a small effect.
|
||||
- Use common limits for panels intended for direct comparison. If limits differ, make the difference unmistakable.
|
||||
- Do not extend axes far beyond observed data merely to suppress visible variation; Science explicitly advises that scales not extend beyond plotted data [SCIENCE-INITIAL].
|
||||
|
||||
### Uncertainty and raw observations
|
||||
|
||||
- Do not add error bars mechanically. Show uncertainty when an estimate is displayed, and show spread when the distribution is the question.
|
||||
- Name the interval precisely: SD, SE, percentile interval, parametric CI, bootstrap CI, posterior interval, or another definition.
|
||||
- State sample size, unit of replication, estimator, interval level, and dependence/repeated-measure handling.
|
||||
- Use deterministic seeds for bootstrap displays. Seaborn 0.13.2 supports `errorbar="sd"`, `"se"`, `"pi"`, `"ci"`, tuples such as `("ci", 95)`, or a callable; bootstrap results vary unless `seed` is set [SEABORN-ERROR].
|
||||
- Show raw observations when feasible. Do not jitter points so far that their category or value becomes ambiguous.
|
||||
- Significance stars are not uncertainty. Add them only for a reported analysis, identify the test and multiplicity handling, and provide exact values where practical.
|
||||
|
||||
### Missing, excluded, and censored data
|
||||
|
||||
- Keep missing values distinct from zero, below-detection-limit values, and excluded observations.
|
||||
- Do not silently connect across missing time points. Use a gap, explicit interpolation style, or a model curve whose status is stated.
|
||||
- Give missing values a dedicated legend entry or neutral `bad` colormap color.
|
||||
- Record exclusions and their rationale outside the plotting code as well as in the caption/methods.
|
||||
|
||||
### Area, volume, and 3D encodings
|
||||
|
||||
- Prefer position on a common scale.
|
||||
- If area represents magnitude, scale **area**, not radius. If volume represents magnitude, scale volume, not diameter.
|
||||
- Avoid perspective 3D bars, pies, and surfaces for simple comparisons; occlusion and perspective distort values.
|
||||
- If a true 3D scientific structure is necessary, add orthogonal views, scale/orientation cues, and accessible alternatives.
|
||||
|
||||
### Logarithms and other transforms
|
||||
|
||||
- Label the transformed scale and base. Say whether values, axes, or model outputs were transformed.
|
||||
- A logarithmic axis requires a declared policy for zero and negative values; never silently discard them.
|
||||
- Interpret equal distances as ratios, not additive differences.
|
||||
- For signed data around zero, consider `SymLogNorm`/a symmetric log axis with a disclosed linear region; for unequal ranges around a meaningful center, consider `TwoSlopeNorm` [MPL-NORM].
|
||||
- Power-law or arbitrary transforms need strong justification and conspicuous disclosure. Matplotlib itself notes that viewers are less familiar with power normalization [MPL-NORM].
|
||||
|
||||
### Binning, smoothing, and aggregation
|
||||
|
||||
- Record bin edges, inclusion convention, bandwidth/window, smoothing method, and whether choices were made before seeing the result.
|
||||
- Show sensitivity to reasonable bin or bandwidth choices when conclusions depend on them.
|
||||
- Do not use interpolation or smoothing to imply observations between measured points.
|
||||
- Preserve and, where practical, expose underlying observations.
|
||||
|
||||
### Normalization and color limits
|
||||
|
||||
- State the formula and reference: per-capita, percent of baseline, z-score axis, library-size factor, min-max range, or other transformation.
|
||||
- Fit normalization parameters on the appropriate data partition; avoid information leakage.
|
||||
- Use the same normalization and color limits across directly compared panels unless the difference is explicit.
|
||||
- A diverging map needs a scientifically meaningful center. `Normalize`, `LogNorm`, `CenteredNorm`, `SymLogNorm`, `TwoSlopeNorm`, and `BoundaryNorm` encode different assumptions [MPL-NORM].
|
||||
- Always label colorbars with units and transformed scale.
|
||||
|
||||
### Dual axes
|
||||
|
||||
Prefer aligned panels or normalized/common-unit displays. Dual y-axes can make unrelated series appear correlated because each range can be tuned independently. If unavoidable:
|
||||
|
||||
- justify the shared x-domain and distinct units;
|
||||
- label each axis and series directly;
|
||||
- avoid matching colors as the only association cue;
|
||||
- choose limits independently of the desired visual relationship;
|
||||
- provide the underlying data.
|
||||
|
||||
### Image contrast and channels
|
||||
|
||||
- Inspect histograms and clipped-pixel counts before and after adjustment.
|
||||
- Apply comparable processing to images being compared.
|
||||
- State channel assignment, lookup table, projection, denoising, deconvolution, thresholding, and contrast limits.
|
||||
- Use scale bars based on calibration, not magnification text.
|
||||
- Do not rely on red/green channel identity alone; use accessible channel combinations, outlines, labels, or separate grayscale panels.
|
||||
|
||||
## Encoding and color
|
||||
|
||||
Match the palette to data:
|
||||
|
||||
- **Qualitative** for unordered categories; do not imply order.
|
||||
- **Sequential** for ordered magnitude.
|
||||
- **Diverging** only when a meaningful midpoint exists.
|
||||
- **Cyclic** for periodic variables such as direction or phase.
|
||||
|
||||
Use hue consistently across a manuscript. Avoid rainbow maps for ordered data unless there is a documented scientific reason and the map has been evaluated for perceptual artifacts. Paul Tol explains why ordinary rainbow schemes create false transitions and fail for some color-vision conditions [TOL].
|
||||
|
||||
Color is not a sufficient encoding:
|
||||
|
||||
- combine it with marker shape, line style, hatching, direct labels, or panel separation;
|
||||
- audit contrast against the actual background;
|
||||
- inspect grayscale, but do not treat grayscale conversion as a complete color-vision simulation;
|
||||
- keep legends ordered like the data or direct-label series.
|
||||
|
||||
See `color_palettes.md` and run `scripts/palette_audit.py`.
|
||||
|
||||
## Accessibility
|
||||
|
||||
WCAG 2.2 is a web-content standard, not a journal-print specification. It provides useful targets for figures delivered on the web [WCAG22]:
|
||||
|
||||
- SC 1.4.1 (Level A): color is not the only visual means of conveying information.
|
||||
- SC 1.4.3 (Level AA): normal text has at least 4.5:1 contrast; large text has at least 3:1, with stated exceptions.
|
||||
- SC 1.4.11 (Level AA): graphical objects required to understand content have at least 3:1 contrast against adjacent colors, with an essential-presentation exception.
|
||||
- SC 1.1.1 (Level A): non-text content has an equivalent text alternative.
|
||||
- SC 1.4.5 (Level AA): use actual text rather than images of text when the technology can provide it, subject to exceptions.
|
||||
|
||||
For web/interactive figures also provide:
|
||||
|
||||
- a concise alt text naming chart type, variables, main pattern, and important exception;
|
||||
- a long description or nearby narrative for complex figures;
|
||||
- the underlying data in an accessible table/download;
|
||||
- keyboard-operable interactions, visible focus, and non-hover access to values;
|
||||
- a static fallback that preserves the scientific message.
|
||||
|
||||
Passing a palette ratio audit does not prove WCAG conformance; applicability depends on rendered context and alternatives.
|
||||
|
||||
## Layout, typography, and annotation
|
||||
|
||||
- Design at final physical size. Judge labels, symbols, and line weights at that size.
|
||||
- Use one legible font family and a restrained size hierarchy.
|
||||
- Include units in axis/colorbar labels. Define abbreviations.
|
||||
- Keep panel labels consistent and outside dense data regions.
|
||||
- Use layout engines intentionally: `layout="constrained"` handles nested grids and colorbars; calling `tight_layout()` disables constrained layout [MPL-LAYOUT].
|
||||
- Check all labels and legends after export. `bbox_inches="tight"` can alter physical page dimensions, so do not use it when exact page width is required [MPL-SAVE].
|
||||
- Keep decorative ink subordinate to data, uncertainty, and annotations. Gridlines can help value lookup when light and sparse; removing them is not a universal rule.
|
||||
|
||||
## Static, vector, raster, and interactive output
|
||||
|
||||
### Vector
|
||||
|
||||
PDF/SVG/EPS are useful for text and line art, but a vector container may include rasterized artists. DPI still controls those raster elements [MPL-SAVE]. EPS/PS cannot preserve partial transparency; choose PDF/SVG or explicitly review an opaque rendering rather than assuming identical appearance. Dense scatter plots can be selectively rasterized to control file size while preserving vector text/axes.
|
||||
|
||||
For Matplotlib:
|
||||
|
||||
```python
|
||||
import matplotlib as mpl
|
||||
|
||||
mpl.rcParams["pdf.fonttype"] = 42
|
||||
mpl.rcParams["ps.fonttype"] = 42
|
||||
mpl.rcParams["svg.fonttype"] = "none"
|
||||
```
|
||||
|
||||
PDF/PS Type 42 embeds TrueType fonts. `svg.fonttype="none"` leaves text as text and therefore depends on font availability; `svg.fonttype="path"` trades editability/searchability for appearance portability [MPL-STYLE]. Inspect the delivered file rather than assuming font behavior.
|
||||
|
||||
### Raster
|
||||
|
||||
Required pixel width is:
|
||||
|
||||
```text
|
||||
pixels = final width (inches) × target pixels per inch
|
||||
```
|
||||
|
||||
Embedded DPI metadata alone does not add detail. TIFF/PNG are lossless choices; JPEG can be accepted by some publishers for photographs but is a poor choice for line art or text because it is lossy. Preserve original bit depth and color profile when scientifically important.
|
||||
|
||||
Transparency can reveal an unintended background or change apparent contrast. Matplotlib's `transparent=True` makes axes patches transparent and, unless explicitly overridden, the figure patch too [MPL-SAVE]. Prefer an explicit opaque background for submission unless the destination requires transparency.
|
||||
|
||||
### Plotly
|
||||
|
||||
- `write_html()` preserves interaction and is self-contained by default; that embeds Plotly.js and creates a large file. `include_plotlyjs` and `full_html=False` change portability and embedding behavior [PLOTLY-HTML].
|
||||
- Static `write_image()` uses Kaleido and supports PNG, JPEG, WebP, SVG, and PDF. Width/height are logical pixels; `scale` changes physical output pixel count, not a journal DPI declaration [PLOTLY-STATIC].
|
||||
- WebGL traces are partly rasterized inside SVG/PDF output [PLOTLY-STATIC].
|
||||
- Export a static, captioned fallback and accessible data alongside interactive output.
|
||||
|
||||
## Final scientific review
|
||||
|
||||
- [ ] Raw data and native images are preserved.
|
||||
- [ ] Transformations, exclusions, normalization, bins, and random seeds are recorded.
|
||||
- [ ] Missing/censored values are explicit.
|
||||
- [ ] Baselines, limits, log scales, and breaks are scientifically justified.
|
||||
- [ ] Uncertainty and sample size are defined.
|
||||
- [ ] Area/volume and color normalization encode magnitude correctly.
|
||||
- [ ] Color is redundant; foreground/background contrast was reviewed.
|
||||
- [ ] Alt text/long description and underlying data are available for web delivery.
|
||||
- [ ] Physical size, raster pixels, fonts, transparency, and file format were inspected after export.
|
||||
- [ ] The current target-journal instructions were checked for the correct submission phase.
|
||||
@@ -0,0 +1,84 @@
|
||||
# Sources and Version Snapshot
|
||||
|
||||
Reviewed 2026-10-01 using official documentation, release source, current PyPI metadata, native synthetic fixtures, and fresh extraction for blocked publisher pages. Science remains a historical snapshot because both retrieval routes failed. ACS is an explicitly dated legacy page, not a current journal rule. No submission, authentication, or publication API is called by these network-free tools.
|
||||
|
||||
## Tested direct package snapshot
|
||||
|
||||
- **Matplotlib 3.11.2**, Python >=3.11 [MPL-PYPI].
|
||||
- **Seaborn 0.13.2**, Python >=3.8 [SEABORN-PYPI].
|
||||
- **Plotly 7.1.0**, Python >=3.8 [PLOTLY-PYPI].
|
||||
- **Kaleido 1.4.0**, Python >=3.8; compatible Chrome/Chromium required [KALEIDO-PYPI].
|
||||
- **Pillow 12.3.0**, Python >=3.10 [PIL-PYPI].
|
||||
- **pypdf 6.19.0**, Python >=3.9 [PYPDF-PYPI].
|
||||
|
||||
Native tests use Python 3.13, synthetic data, and local Matplotlib/Pillow/pypdf outputs. Plotly HTML and Kaleido exports are checked separately; the isolated baseline manifest does not install optional Kaleido. These direct pins are not a transitive lock. GUI, TeX/PGF, optional Cairo, color-managed printing, authenticated journal submission, and arbitrary external-asset rendering are not established by these checks.
|
||||
|
||||
## Matplotlib
|
||||
|
||||
- **[MPL-PYPI]** [matplotlib on PyPI](https://pypi.org/project/matplotlib/) — current package version and release history.
|
||||
- **[MPL-RELEASE]** [Matplotlib release notes](https://matplotlib.org/stable/release/release_notes.html) — 3.11 release/API changes.
|
||||
- **[MPL-SAVE]** [`matplotlib.figure.Figure.savefig`](https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.savefig.html) — 3.11.2 signature; format inference, DPI, metadata, bounding boxes, transparency, backends, Pillow kwargs.
|
||||
- **[MPL-BACKENDS]** [Backends](https://matplotlib.org/stable/users/explain/figure/backends.html) — interactive versus static renderers; PDF/PS/SVG/PGF/Cairo formats.
|
||||
- **[MPL-STYLE]** [Customizing Matplotlib with style sheets and rcParams](https://matplotlib.org/stable/users/explain/customizing.html) — `rc_context`, style composition, save settings, PDF/PS/SVG font types.
|
||||
- **[MPL-LAYOUT]** [Constrained layout guide](https://matplotlib.org/stable/users/explain/axes/constrainedlayout_guide.html) — `layout="constrained"`, colorbars, subfigures, GridSpec, interaction with `tight_layout`.
|
||||
- **[MPL-GRIDSPEC]** [`matplotlib.gridspec`](https://matplotlib.org/stable/api/gridspec_api.html) — current grid layout API.
|
||||
- **[MPL-NORM]** [Colormap normalization](https://matplotlib.org/stable/users/explain/colors/colormapnorms.html) — `Normalize`, `LogNorm`, `CenteredNorm`, `SymLogNorm`, `PowerNorm`, `BoundaryNorm`, `TwoSlopeNorm`.
|
||||
- **[MPL-CMAP]** [Choosing colormaps](https://matplotlib.org/stable/users/explain/colors/colormaps.html) — data classes and perceived lightness.
|
||||
|
||||
## Seaborn
|
||||
|
||||
- **[SEABORN-PYPI]** [seaborn on PyPI](https://pypi.org/project/seaborn/) — 0.13.2 package metadata and release history.
|
||||
- **[SEABORN-ERROR]** [Statistical estimation and error bars](https://seaborn.pydata.org/tutorial/error_bars.html) — current `errorbar` methods, callable intervals, bootstrapping, `seed`, and `n_boot`.
|
||||
- **[SEABORN-FAQ]** [Frequently asked questions](https://seaborn.pydata.org/faq.html) — axes-level versus figure-level functions, Matplotlib object-oriented integration, DPI/SVG notes.
|
||||
- **[SEABORN-PALETTE]** [Choosing color palettes](https://seaborn.pydata.org/tutorial/color_palettes.html) — qualitative, sequential, and diverging palette APIs.
|
||||
- **[SEABORN-THEME]** [`seaborn.set_theme`](https://seaborn.pydata.org/generated/seaborn.set_theme.html) — style, context, palette, font, scale, and rc parameters.
|
||||
|
||||
## Plotly and Kaleido
|
||||
|
||||
- **[PLOTLY-PYPI]** [plotly on PyPI](https://pypi.org/project/plotly/) — 7.1.0 package metadata.
|
||||
- **[PLOTLY-STATIC]** [Static image export in Python](https://plotly.com/python/static-image-export/) — Kaleido/Chrome setup, formats, `write_image`, `write_images`, dimensions/scale, WebGL rasterization, offline assets, defaults, EPS/Orca/engine deprecations; page dated 2026.
|
||||
- **[PLOTLY-HTML]** [Interactive HTML export](https://plotly.com/python/interactive-html-export/) — `write_html`, `to_html`, `include_plotlyjs`, `full_html`; page dated 2026.
|
||||
- **[PLOTLY-CHANGES]** [Static image generation changes in Plotly.py 6.1](https://plotly.com/python/static-image-generation-changes/) — Kaleido v1 migration and deprecations.
|
||||
- **[KALEIDO]** [Plotly Kaleido repository](https://github.com/plotly/Kaleido) — Chrome requirement, v1 migration, direct APIs, and offline/page behavior.
|
||||
- **[KALEIDO-PYPI]** [kaleido on PyPI](https://pypi.org/project/kaleido/) — 1.4.0 package metadata.
|
||||
|
||||
- **[PLOTLY-7]** [Plotly 7.0 release](https://github.com/plotly/plotly.py/releases/tag/v7.0.0) — removal of Orca, Kaleido v0, and `engine`; MathJax 2 removal and Share Chart button.
|
||||
- **[KALEIDO-14]** [Kaleido 1.4 release](https://github.com/plotly/Kaleido/releases/tag/v1.4.0) — MathJax default moves to v3.
|
||||
|
||||
## Accessibility and color
|
||||
|
||||
- **[WCAG22]** [Web Content Accessibility Guidelines (WCAG) 2.2](https://www.w3.org/TR/WCAG22/) — W3C Recommendation; normative SC 1.1.1, 1.4.1, 1.4.3, 1.4.5, and 1.4.11.
|
||||
- **[WCAG-NONTEXT]** [Understanding SC 1.4.11: Non-text Contrast](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html) — informative chart/graph examples and testing principles; not itself normative.
|
||||
- **[WCAG-COLOR]** [Understanding SC 1.4.1: Use of Color](https://www.w3.org/WAI/WCAG22/Understanding/use-of-color.html) — informative non-color cue guidance.
|
||||
- **[COLORBREWER]** [ColorBrewer 2.0](https://colorbrewer2.org/) — Cynthia Brewer, Mark Harrower, and Penn State; scheme type, data-class count, colorblind/print/photocopy filters, and exports.
|
||||
- **[TOL-HOME]** [Paul Tol’s Notes](https://sronpersonalpages.nl/~pault/) — canonical site; page states the move from SRON on 2026-07-07.
|
||||
- **[TOL]** [Paul Tol, “Colour Schemes”](https://sronpersonalpages.nl/~pault/data/colourschemes.pdf) — SRON/EPS/TN/09-002, issue 3.2, 2021-08-18; exact sRGB palettes, intended uses, color-vision checks, and grayscale analysis.
|
||||
- **[WONG]** [Bang Wong, “Color blindness”](https://www.nature.com/articles/nmeth.1618) — Nature Methods 8, 441 (2011); source commonly used for the eight-color palette.
|
||||
|
||||
## Publishers and journals
|
||||
|
||||
Most publisher content was verified 2026-10-01. Nature final submission and Cell Press needed fresh extraction after direct access failed. Science initial/revised pages remained blocked; their 2026-07-23 values are explicitly historical. ACS is a legacy source updated 2006-01-21. Dates label access separately from publication dates.
|
||||
|
||||
- **[NATURE-FINAL]** [`Nature` final submission](https://www.nature.com/nature/for-authors/final-submission) — flagship final files, dimensions, fonts, formats, raster resolution, RGB/CMYK, Extended Data distinctions.
|
||||
- **[NATURE-FIG]** [`Nature` research figure specifications](https://research-figure-guide.nature.com/figures/preparing-figures-our-specifications) — graphs, accessibility, RGB, 300/450 dpi discussion, editable Type 42 text, export.
|
||||
- **[SCIENCE-INITIAL]** [`Science` initial manuscript instructions](https://www.science.org/content/page/instructions-preparing-initial-manuscript) — historical snapshot: initial figure embedding, 300 dpi, widths, fonts, color/contrast, source data.
|
||||
- **[SCIENCE-REVISED]** [`Science` revised manuscript instructions](https://www.science.org/content/page/instructions-preparing-revised-manuscript) — historical snapshot: separate files, formats, minimum resolution, dimensions, no upsampling.
|
||||
- **[CELL-FIG]** [Cell Press figure guidelines](https://www.cell.com/information-for-authors/figure-guidelines) — initial versus final stages, formats, widths, file size, DPI, RGB, fonts, image integrity, AI-assisted image policy.
|
||||
- **[PLOS-FIG]** [PLOS Computational Biology figures](https://journals.plos.org/ploscompbiol/s/figures) — provisional-accept waiver, TIFF/EPS, dimensions, 300-600 dpi, RGB/grayscale, file size, image integrity, 2026-04-01 blot/gel requirement.
|
||||
- **[ELSEVIER-FORMAT]** [Elsevier artwork formats checklist](https://www.elsevier.com/about/policies-and-standards/author/artwork-and-media-instructions/artwork-formats-checklist) — general formats, RGB preference, separate files, journal override.
|
||||
- **[ELSEVIER-SIZE]** [Elsevier artwork sizing](https://www.elsevier.com/about/policies-and-standards/author/artwork-and-media-instructions/artwork-sizing) — general widths, 300/500/1,000 dpi, typography, and explicit journal variability.
|
||||
- **[IEEE-SIZE]** [IEEE Resolution and Size](https://journals.ieeeauthorcenter.ieee.org/create-your-ieee-journal-article/create-graphics-for-your-article/resolution-and-size/) — modified 2025-02-25; PS/EPS/PDF, >300/>600 dpi, 88.9/182 mm.
|
||||
- **[BMC-BIOINFO]** [BMC Bioinformatics: preparing your manuscript](https://link.springer.com/journal/12859/submission-guidelines) — journal-specific formats, 85/170 mm, approximately 300 dpi, 10 MB, embedded fonts.
|
||||
- **[ACS-GRAPHICS]** [ACS Preparing Manuscript Graphics](https://pubsapp.acs.org/paragonplus/submission/general/graphics_prep.html) — legacy dimensions/typography, page updated 2006-01-21; target-journal rules govern.
|
||||
|
||||
## Optional inspection backends
|
||||
|
||||
- **[PIL-PYPI]** [Pillow on PyPI](https://pypi.org/project/Pillow/) — 12.3.0 package metadata; released 2026-07-01.
|
||||
- **[PYPDF-PYPI]** [pypdf on PyPI](https://pypi.org/project/pypdf/) — 6.19.0 package metadata.
|
||||
|
||||
- **[PIL-IMAGE]** [Pillow Image API](https://pillow.readthedocs.io/en/stable/reference/Image.html) — lazy open, verify versus decoding, channel conversion, pixel limits.
|
||||
- **[PIL-TIFF]** [Pillow TIFF format](https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#tiff) — LZW compression, DPI, ICC, multiple frames.
|
||||
- **[PYPDF-PAGE]** [pypdf PageObject](https://pypdf.readthedocs.io/en/stable/modules/PageObject.html) — `user_unit`, `rotation`, `mediabox`, and `cropbox`; page coordinates alone are not physical size.
|
||||
- **[SEABORN-LINE]** [seaborn.lineplot](https://seaborn.pydata.org/generated/seaborn.lineplot.html) — `units` with `estimator=None` for individual trajectories; missing rows can be dropped before line construction, so use explicit Matplotlib gaps for missing observations.
|
||||
|
||||
Native checks verify technical behavior, not truth of data, inferential calibration, full-file accessibility, or publisher acceptance. The PDF inspector reports only first-page declared font resources; it does not traverse nested XObjects or all pages. Source artifacts and smoke outputs stay outside the shipped skill.
|
||||
Reference in New Issue
Block a user