[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7DBZCK80S564CW20SXJGX2P":3,"skill-same:01M7DBZCK80S564CW20SXJGX2P":52},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":5,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":29,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7DBZCK80S564CW20SXJGX2P","matplotlib",null,"Create, improve, or reproduce Matplotlib charts with deliberate styling, typography, annotations, custom layouts, and maps. Use when producing Python visualizations or refining existing Matplotlib, Seaborn, or GeoPandas figures.","holtzy\u002Fdataviz-skills","holtzy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F10254401?v=4","01M7DBYM5PP8FX5TBCC2P50RC5","Holtz Yan","01M7DBYM6BV0BBEC3DVNWEQG1Y",20,"MIT","https:\u002F\u002Fgithub.com\u002Fholtzy\u002Fdataviz-skills\u002Fblob\u002Fmain\u002Fmatplotlib\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: matplotlib\ndescription: Create, improve, or reproduce Matplotlib charts with deliberate styling, typography, annotations, custom layouts, and maps. Use when producing Python visualizations or refining existing Matplotlib, Seaborn, or GeoPandas figures.\n---\n\n- Rank categories by a meaningful measure; preserve chronological, ordinal, or domain order when it matters. Prefer horizontal bars or dots to crowded category labels.\n- For distributions, examine bin width or KDE bandwidth; a change in smoothing can change the apparent story. Show individual observations when a summary hides meaningful structure.\n- For many groups, use small multiples or highlight a few groups over muted context. Twenty distinguishable colors rarely solve a crowded chart.\n- Let the message justify unusual forms. Matplotlib can combine primitives: a dumbbell is `ax.hlines()` plus two `ax.scatter()` calls; a confidence band is `ax.fill_between()`. A bespoke chart does not always need a bespoke library.\n\nUse [Data to Viz](https:\u002F\u002Fwww.data-to-viz.com\u002F) when chart choice is uncertain, [Python Graph Gallery](https:\u002F\u002Fpython-graph-gallery.com\u002F) for implementation patterns, and [Dataviz Inspiration](https:\u002F\u002Fwww.dataviz-inspiration.com\u002F) for composition ideas. Borrow visual structure while preserving the meaning of the actual data.\n\n## Construct the figure deliberately\n\nUse explicit Figure and Axes objects throughout: `fig, ax = plt.subplots(...)`, `ax.plot(...)`, `fig.savefig(...)`. Pass `ax=ax` to compatible third-party plotting functions. This makes layering and multi-panel work predictable. Keep data preparation separate from presentation; reusable plotting functions should accept an Axes or return the figure and axes they create.\n\nChoose figure dimensions for the final reading size. Increasing export DPI does not fix text that becomes too small when the image is embedded in a report or webpage.\n\nChoose one layout strategy:\n\n- For ordinary grids, use `layout=\"tight\"`; `layout=\"constrained\"` is useful for layouts involving shared colorbars or panels spanning rows and columns.\n- For an editorial figure with a manually positioned header, footer, or closely packed marginal plots, use `layout=None` and `fig.subplots_adjust(...)`. Reserve space for text explicitly.\n- Avoid mixing automatic layout with manual `subplots_adjust()` calls. Automatic layout also does not guarantee that arbitrary `fig.text()` annotations receive enough space.\n\nSee the [layout guide](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fusers\u002Fexplain\u002Faxes\u002Fconstrainedlayout_guide.html) when a layout engine interferes with positioning.\n\n## Style for the reading task\n\nRemove visual competition around the data. Usually hide the top and right spines; for a labeled bar chart, removing all spines can work better. Remove tick marks while retaining useful tick labels. Put subtle gridlines behind the marks, along the quantitative axis: vertical gridlines for horizontal bars, horizontal gridlines for vertical bars.\n\n```python\nax.spines[[\"top\", \"right\"]].set_visible(False)\nax.tick_params(length=0, pad=8)\nax.set_axisbelow(True)\nax.grid(axis=\"x\", color=\"#dddddd\", linewidth=0.6)  # horizontal bars\n```\n\nUse a zero baseline for bars and area encodings of magnitude. For line and scatter charts, choose limits that reveal the relevant variation without silently hiding observations. Format units and percentages explicitly. Reduce tick density, wrap labels, or change orientation before rotating every label.\n\nApply a theme before creating artists, then make chart-specific adjustments. Keep figure and axes backgrounds consistent unless their difference serves a purpose. Use `plt.rc_context({...})` or `plt.style.context(...)` to scope reusable styles; a property cycle provides defaults, but an explicit mapping is better when group identities must remain stable across charts.\n\n**morethemes** supplies coherent themes such as `ft`, `urban`, and `economist`. Use one as a starting point, then adjust hierarchy and spacing for the actual chart. `mt.set_theme(\"ft\")` applies a theme globally and resets defaults first; for scoped use:\n\n```python\nimport matplotlib.pyplot as plt\nimport morethemes as mt\n\nwith plt.rc_context(mt.get_rcparams(\"ft\")):\n    fig, ax = plt.subplots(figsize=(8, 4), layout=\"constrained\")\n    ax.plot(x, y)\n```\n\n[morethemes documentation](https:\u002F\u002Fy-sunflower.github.io\u002Fmorethemes\u002Fguide\u002Freference\u002F). Native [style sheets and rcParams](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fusers\u002Fexplain\u002Fcustomizing.html) are sufficient when only a few settings need changing.\n\n## Make visual mappings explicit\n\nChoose color for a specific job: distinguish categories, encode quantities, or highlight a finding. Use a qualitative palette for groups, a perceptually ordered sequential palette for magnitudes, and a diverging palette around a meaningful reference value. A continuous colormap made from categorical colors does not become a meaningful quantitative scale merely because it is interpolated.\n\nFor explanation, start with muted context and one or two accent colors. Avoid a different color for every bar when position already identifies the categories. Check contrast against the actual background; use labels, marker shapes, line styles, or hatching when color alone is insufficient.\n\nPreserve category-to-color mappings across sorting, filtering, panels, and separate figures:\n\n```python\npalette = {\"North\": \"#335c67\", \"South\": \"#ae2f2f\"}\nax.scatter(df[\"x\"], df[\"y\"], color=df[\"region\"].map(palette))\n\n# Highlight a condition without removing the rest of the data.\ncolors = df[\"region\"].eq(\"North\").map({True: \"#335c67\", False: \"#d3d3d3\"})\n```\n\nFor numeric color, pass the values to `c`, the colormap to `cmap`, and retain the returned mappable for `fig.colorbar(mappable, ax=ax, label=...)`. Set shared `norm` or `vmin`\u002F`vmax` across comparable panels. Use `TwoSlopeNorm(vmin=..., vcenter=0, vmax=...)` for a diverging scale centered on zero when values span both sides. Do not rescale each panel independently without communicating it.\n\n**pypalettes** provides curated palettes and Matplotlib colormaps. Prefer a named palette chosen for the data over inventing a multicolor scheme. Use the discrete palette's `.colors` for categorical mappings and a continuous colormap for numeric values:\n\n```python\nfrom pypalettes import load_cmap\n\npalette = load_cmap(\"Acadia\").colors\ncmap = load_cmap(\"BluGrn\", cmap_type=\"continuous\")\npoints = ax.scatter(df[\"x\"], df[\"y\"], c=df[\"value\"], cmap=cmap)\n```\n\n[pypalettes API](https:\u002F\u002Fy-sunflower.github.io\u002Fpypalettes\u002Freference\u002Fload_cmap\u002F) and [palette finder](https:\u002F\u002Fpython-graph-gallery.com\u002Fcolor-palette-finder\u002F). Select a fixed name for reproducible output; avoid a random palette.\n\nFor bubble charts, `scatter(s=...)` encodes marker area in points squared. If bubble area represents magnitude, use `s = scale * values`, not a radius proportional to values. A min\u002Fmax size remapping changes proportional relationships; if needed, communicate that mapping and use it consistently in the size legend. Draw large bubbles first and small bubbles last; use opacity to expose overlap.\n\n## Compose text as part of the chart\n\nPrefer `fig.text()` and `ax.text()` for custom titles, subtitles, direct labels, and notes because their placement is flexible. Use a takeaway title supported by the data, a quieter subtitle for scope and units, and a small source note. Align these blocks with the plotting area or a consistent figure margin. Use a clear size\u002Fweight hierarchy rather than many font families.\n\nChoose coordinates according to what the annotation belongs to:\n\n| Placement | API \u002F transform | Useful for |\n| --- | --- | --- |\n| Data coordinates | `ax.text(x, y, ...)` | End-of-line labels, outliers, extrema |\n| Relative to the panel, 0–1 | `ax.text(..., transform=ax.transAxes)` | Panel names, stable corner notes |\n| Relative to the figure, 0–1 | `fig.text(x, y, ...)` | Shared title, subtitle, caption |\n\nSet `ha` and `va` deliberately. For a label attached to a point, `ax.annotate(..., xytext=(6, 0), textcoords=\"offset points\")` gives a stable physical offset. Use `clip_on=False` when an artist should extend beyond its Axes, and leave enough room in the figure. See the [transforms tutorial](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fusers\u002Fexplain\u002Fartists\u002Ftransforms_tutorial.html) for mixed coordinate systems.\n\nDirectly label a manageable number of lines, bars, or groups near their marks, matching label colors to the data. Reserve space for endpoint labels instead of placing them against the figure edge. Keep a legend when direct labels would crowd the data or when readers need a numeric color or size key. A continuous color scale normally needs a labeled colorbar. Build a manual legend only when its custom layout materially helps.\n\n**highlight_text** handles several colors, weights, or fonts inside one annotation. Use it to turn a title or sentence into a compact color key rather than positioning separate text fragments by eye:\n\n```python\nfrom highlight_text import fig_text\n\nfig_text(\n    x=0.12, y=0.94, s=\"\u003CNorth> grows while \u003CSouth> declines\",\n    highlight_textprops=[{\"color\": \"#335c67\"}, {\"color\": \"#ae2f2f\"}],\n    fig=fig, fontsize=18, ha=\"left\", va=\"top\",\n)\n```\n\nProvide one properties dictionary per `\u003Chighlighted substring>`. `ax_text(..., ax=ax)` uses data coordinates; `fig_text(..., fig=fig)` uses figure coordinates. [highlight_text documentation](https:\u002F\u002Fgithub.com\u002Fznstrider\u002Fhighlight_text#use).\n\n**pyfonts** loads fonts reproducibly as `FontProperties` objects. Prefer the named Google\u002FBunny loaders over searching repositories for font-file URLs. Load the actual weights and styles required by the design; setting `weight=\"bold\"` on text referencing a specific regular font file does not select a different file.\n\n```python\nfrom pyfonts import load_google_font\n\nregular = load_google_font(\"Roboto\")\nbold = load_google_font(\"Roboto\", weight=\"bold\")\nfig.text(0.12, 0.94, \"The supported takeaway\", font=bold, fontsize=20)\nax.text(0.02, 0.95, \"Panel A\", transform=ax.transAxes, font=regular, va=\"top\")\n```\n\nUse `load_font(local_path_or_url)` for an existing font asset; `set_default_font(regular)` applies it to future ticks, labels, and other text. Load fonts before final layout and inspection because font metrics affect spacing. [pyfonts documentation](https:\u002F\u002Fy-sunflower.github.io\u002Fpyfonts\u002F).\n\n**drawarrow** simplifies curved annotation arrows without juggling Matplotlib's several arrow APIs. Use it when a curved connector helps connect a note to a finding; keep its visual weight subordinate to the data:\n\n```python\nfrom drawarrow import ax_arrow\n\nax_arrow(\n    tail_position=(2, 8), head_position=(4, 5),\n    radius=0.25, color=\"#555555\", ax=ax,\n)\n```\n\n`ax_arrow` uses data coordinates; `fig_arrow` is useful for figure-relative connectors. [drawarrow documentation](https:\u002F\u002Fy-sunflower.github.io\u002Fdrawarrow\u002F). For a simple native callout, `ax.annotate()` may already suffice.\n\nFor contextual bands and reference lines, use `ax.axvspan()`, `ax.axhspan()`, `ax.axvline()`, or `ax.axhline()` with subdued styling. For other shapes, add patches with an explicit transform and `zorder`. A decorative arrow or shaded region should explain something specific.\n\n## Use statistical extensions where they reduce work\n\n**Seaborn** supplies grouping and statistical calculations for KDEs, violins, swarms, regression fits, and more. Let it construct the data layer, then finish the composition through Matplotlib. Use axes-level functions when integrating into an existing figure:\n\n```python\nimport seaborn as sns\n\nsns.scatterplot(\n    data=df, x=\"x\", y=\"y\", hue=\"region\", style=\"region\",\n    palette={\"North\": \"#335c67\", \"South\": \"#ae2f2f\"}, ax=ax,\n)\n# A separate distribution example:\n# sns.kdeplot(data=df, x=\"value\", hue=\"region\", fill=True, ax=ax)\n```\n\nCheck statistical defaults before accepting the result: `sns.lineplot()` aggregates repeated x-values and adds confidence intervals by default. Use `estimator=None, errorbar=None` for an already prepared series, and `units=` when distinct trajectories must remain separate. For categorical totals already computed, `ax.barh()` avoids accidental re-aggregation.\n\n`pairplot`, `jointplot`, `relplot`, `displot`, and `catplot` manage their own figures\u002Fgrids; do not treat them as axes-level functions accepting `ax=`. They are useful for exploration, while a manual layout gives more control over a finished explanatory figure. [Seaborn API](https:\u002F\u002Fseaborn.pydata.org\u002Fapi.html), [function overview](https:\u002F\u002Fseaborn.pydata.org\u002Ftutorial\u002Ffunction_overview.html), and [lineplot defaults](https:\u002F\u002Fseaborn.pydata.org\u002Fgenerated\u002Fseaborn.lineplot.html).\n\n## Build layouts around comparisons\n\nUse `plt.subplots()` for regular grids and `plt.subplot_mosaic()` for asymmetric layouts with named panels. Repeated mosaic labels make one Axes span cells; `\".\"` leaves a gap. Prefer these readable layouts before reaching for low-level positioning.\n\n```python\nfig, axs = plt.subplot_mosaic(\n    [[\"main\", \"detail\"], [\"main\", \"distribution\"]],\n    figsize=(10, 6), width_ratios=[2, 1], layout=\"constrained\",\n)\naxs[\"main\"].plot(x, y)\ninset = axs[\"main\"].inset_axes([0.6, 0.12, 0.32, 0.28])\n```\n\nFor small multiples, iterate over groups and axes (`zip(groups, axs.flat)`); `squeeze=False` gives a consistent two-dimensional array even for a single panel. Rank panels intentionally, share axis limits and visual mappings when comparing magnitudes, label each panel inside the Axes, and hide unused panels. Optionally show all other groups as faint background traces in each panel. If scales differ, make that difference conspicuous.\n\nAn inset's bounds are `[left, bottom, width, height]` relative to its parent Axes by default. Use it for a secondary distribution, map detail, compact visual key, or relevant image. For logos\u002Fimages, call `inset.imshow(image)` and `inset.set_axis_off()`; keep the image from competing with the marks. [Mosaic guide](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fusers\u002Fexplain\u002Faxes\u002Fmosaic.html) and [inset API](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fapi\u002F_as_gen\u002Fmatplotlib.axes.Axes.inset_axes.html).\n\n## Treat maps as layered charts with a CRS\n\n**GeoPandas** reads geographic files, joins attributes to geometries, reprojects them, and draws boundaries or choropleths onto a Matplotlib Axes. Start with the geometry table on the left of the join to preserve its geospatial behavior. For one metric per region, validate the join cardinality and inspect unmatched identifiers; show missing values distinctly from zero.\n\n```python\nimport geopandas as gpd\n\nregions = gpd.read_file(\"regions.geojson\")\nmapped = regions.merge(metrics, on=\"region_id\", how=\"left\", validate=\"one_to_one\")\nmapped.plot(\n    column=\"rate\", cmap=\"viridis\", legend=True, ax=ax,\n    edgecolor=\"white\", linewidth=0.4,\n    missing_kwds={\"color\": \"#eeeeee\", \"label\": \"No data\"},\n)\nax.set_axis_off()\n```\n\n[GeoPandas mapping guide](https:\u002F\u002Fgeopandas.org\u002Fen\u002Fstable\u002Fdocs\u002Fuser_guide\u002Fmapping.html).\n\n- Choropleths generally need a rate, proportion, or density; absolute totals often mostly reflect population. When totals are the message, consider proportional symbols instead. Large geographic regions can dominate perception even when few people live there.\n- Use the same color normalization or classification boundaries for maps that readers should compare. Explain the units and any bins; keep missing regions visible.\n- Use `to_crs(...)` to transform coordinates. `set_crs(...)` declares what existing coordinates mean and does not transform them. Choose projections for the task; Mercator is unsuitable for comparing world region areas.\n- For bubble maps, convert longitude\u002Flatitude to point geometries with `gpd.points_from_xy(...)`, assign their known source CRS, and reproject to the map CRS before plotting. Changing the basemap projection alone does not move raw scatter coordinates.\n- For region labels, use projected coordinates for centroid calculations; `representative_point()` is often better when a label must lie inside its region.\n\n**Cartopy** is useful for projection-aware Matplotlib GeoAxes, coastlines, graticules, and global maps. The Axes `projection=` describes the display; each data layer's `transform=` describes its source coordinates. For example, longitude\u002Flatitude points on a Robinson GeoAxes need `ax.scatter(lon, lat, transform=ccrs.PlateCarree(), ...)`. Import projections with `import cartopy.crs as ccrs`. [Cartopy CRS documentation](https:\u002F\u002Fcartopy.readthedocs.io\u002Fstable\u002Freference\u002Fcrs.html). GeoPandas with an appropriate `to_crs()` can suffice when a projected polygon map is all that is needed.\n\n## Reach for specialized tools selectively\n\n**PyWaffle** draws waffle and pictogram charts into an existing Axes. It handles block allocation, spacing, and icons; specify the scale and remember that fitting values into a fixed grid can introduce rounding.\n\n```python\nfrom pywaffle import Waffle\n\nWaffle.make_waffle(ax=ax, rows=5, columns=10, values=[30, 16, 4])\nax.set_aspect(\"equal\")\nax.set_axis_off()\n```\n\n[PyWaffle documentation](https:\u002F\u002Fpywaffle.readthedocs.io\u002Fen\u002Flatest\u002Fquickstart.html). In small multiples, keep the meaning of one block consistent if readers should compare absolute quantities.\n\n**plotnine** offers a grammar-of-graphics interface for layered charts and faceting. Use it when mappings and facets express the chart more clearly than manual Axes loops; `fig = p.draw()` returns a Matplotlib Figure for final annotations or insets. [plotnine documentation](https:\u002F\u002Fplotnine.org\u002F) and [the draw bridge](https:\u002F\u002Fplotnine.org\u002Freference\u002Fggplot.html#draw).\n\n**ninejs** adds hover tooltips, linked highlighting, and click interactions to plotnine charts and exports standalone HTML. Use it when browser interaction is part of the requested deliverable. It works with plotnine objects rather than arbitrary Matplotlib Figures. Consult its [documentation](https:\u002F\u002Fy-sunflower.github.io\u002Fninejs\u002F) for the interaction API supported by the installed version.\n\nFor truly custom curves, use native `matplotlib.path.Path` and `PathPatch`: quadratic Bézier segments use two `CURVE3` entries (control point, endpoint); cubic segments use three `CURVE4` entries (two control points, endpoint). Prefer a dedicated chart library for standard flow diagrams; build paths when the visual design needs custom geometry. See the [Path tutorial](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fusers\u002Fexplain\u002Fartists\u002Fpaths.html). Do not smooth observed time series merely to make them more attractive if the curve would imply unsupported intermediate behavior.\n\n## Inspect the artifact, then refine it\n\nRender and open the exported chart at its intended display size. Check text collisions, clipping, title\u002Fsubtitle spacing, label contrast, line endpoints, legend interpretation, and whether the main comparison is obvious. Refine the actual figure rather than relying on code inspection or successful execution.\n\nSave through `fig.savefig(...)`: PNG for raster delivery, SVG\u002FPDF when vector output is useful. Set DPI for raster output and preserve the intended background with `facecolor=fig.get_facecolor()`. `bbox_inches=\"tight\"` helps include outside annotations but changes the exported bounding dimensions; omit it when exact canvas dimensions are required and fit everything inside the canvas instead.\n\nFor reusable chart pipelines, inspect meaningful artist properties as needed: `fig.axes`, `ax.lines`, `ax.collections`, `ax.patches`, or `ax.get_children()`. Test the intended data and visual contract rather than every styling detail. Colorbars can add Axes, so an Axes count is not automatically a panel count. Artist checks complement visual inspection.\n\nWhen an undocumented-looking keyword is needed, inspect the underlying artist's documentation: `ax.plot()` creates `Line2D` artists, `ax.scatter()` returns a `PathCollection`, and shapes are patches. Their supported properties explain many `**kwargs` in the high-level API. Use the [Axes reference](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fapi\u002Faxes_api.html) to find the plotting method, then follow its returned artist type for precise styling options.\n","- Rank categories by a meaningful measure; preserve chronological, ordinal, or domain order when it matters. Prefer horizontal bars or dots to crowded category labels.\n- For distributions, examine bin width or KDE bandwidth; a change in smoothing can change the apparent story. Show individual observations when a summary hides meaningful structure.\n- For many groups, use small multiples or highlight a few groups over muted context. Twenty distinguishable colors rarely solve a crowded chart.\n- Let the message justify unusual forms. Matplotlib can combine primitives: a dumbbell is `ax.hlines()` plus two `ax.scatter()` calls; a confidence band is `ax.fill_between()`. A bespoke chart does not always need a bespoke library.\n\nUse [Data to Viz](https:\u002F\u002Fwww.data-to-viz.com\u002F) when chart choice is uncertain, [Python Graph Gallery](https:\u002F\u002Fpython-graph-gallery.com\u002F) for implementation patterns, and [Dataviz Inspiration](https:\u002F\u002Fwww.dataviz-inspiration.com\u002F) for composition ideas. Borrow visual structure while preserving the meaning of the actual data.\n\n## Construct the figure deliberately\n\nUse explicit Figure and Axes objects throughout: `fig, ax = plt.subplots(...)`, `ax.plot(...)`, `fig.savefig(...)`. Pass `ax=ax` to compatible third-party plotting functions. This makes layering and multi-panel work predictable. Keep data preparation separate from presentation; reusable plotting functions should accept an Axes or return the figure and axes they create.\n\nChoose figure dimensions for the final reading size. Increasing export DPI does not fix text that becomes too small when the image is embedded in a report or webpage.\n\nChoose one layout strategy:\n\n- For ordinary grids, use `layout=\"tight\"`; `layout=\"constrained\"` is useful for layouts involving shared colorbars or panels spanning rows and columns.\n- For an editorial figure with a manually positioned header, footer, or closely packed marginal plots, use `layout=None` and `fig.subplots_adjust(...)`. Reserve space for text explicitly.\n- Avoid mixing automatic layout with manual `subplots_adjust()` calls. Automatic layout also does not guarantee that arbitrary `fig.text()` annotations receive enough space.\n\nSee the [layout guide](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fusers\u002Fexplain\u002Faxes\u002Fconstrainedlayout_guide.html) when a layout engine interferes with positioning.\n\n## Style for the reading task\n\nRemove visual competition around the data. Usually hide the top and right spines; for a labeled bar chart, removing all spines can work better. Remove tick marks while retaining useful tick labels. Put subtle gridlines behind the marks, along the quantitative axis: vertical gridlines for horizontal bars, horizontal gridlines for vertical bars.\n\n```python\nax.spines[[\"top\", \"right\"]].set_visible(False)\nax.tick_params(length=0, pad=8)\nax.set_axisbelow(True)\nax.grid(axis=\"x\", color=\"#dddddd\", linewidth=0.6)  # horizontal bars\n```\n\nUse a zero baseline for bars and area encodings of magnitude. For line and scatter charts, choose limits that reveal the relevant variation without silently hiding observations. Format units and percentages explicitly. Reduce tick density, wrap labels, or change orientation before rotating every label.\n\nApply a theme before creating artists, then make chart-specific adjustments. Keep figure and axes backgrounds consistent unless their difference serves a purpose. Use `plt.rc_context({...})` or `plt.style.context(...)` to scope reusable styles; a property cycle provides defaults, but an explicit mapping is better when group identities must remain stable across charts.\n\n**morethemes** supplies coherent themes such as `ft`, `urban`, and `economist`. Use one as a starting point, then adjust hierarchy and spacing for the actual chart. `mt.set_theme(\"ft\")` applies a theme globally and resets defaults first; for scoped use:\n\n```python\nimport matplotlib.pyplot as plt\nimport morethemes as mt\n\nwith plt.rc_context(mt.get_rcparams(\"ft\")):\n    fig, ax = plt.subplots(figsize=(8, 4), layout=\"constrained\")\n    ax.plot(x, y)\n```\n\n[morethemes documentation](https:\u002F\u002Fy-sunflower.github.io\u002Fmorethemes\u002Fguide\u002Freference\u002F). Native [style sheets and rcParams](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fusers\u002Fexplain\u002Fcustomizing.html) are sufficient when only a few settings need changing.\n\n## Make visual mappings explicit\n\nChoose color for a specific job: distinguish categories, encode quantities, or highlight a finding. Use a qualitative palette for groups, a perceptually ordered sequential palette for magnitudes, and a diverging palette around a meaningful reference value. A continuous colormap made from categorical colors does not become a meaningful quantitative scale merely because it is interpolated.\n\nFor explanation, start with muted context and one or two accent colors. Avoid a different color for every bar when position already identifies the categories. Check contrast against the actual background; use labels, marker shapes, line styles, or hatching when color alone is insufficient.\n\nPreserve category-to-color mappings across sorting, filtering, panels, and separate figures:\n\n```python\npalette = {\"North\": \"#335c67\", \"South\": \"#ae2f2f\"}\nax.scatter(df[\"x\"], df[\"y\"], color=df[\"region\"].map(palette))\n\n# Highlight a condition without removing the rest of the data.\ncolors = df[\"region\"].eq(\"North\").map({True: \"#335c67\", False: \"#d3d3d3\"})\n```\n\nFor numeric color, pass the values to `c`, the colormap to `cmap`, and retain the returned mappable for `fig.colorbar(mappable, ax=ax, label=...)`. Set shared `norm` or `vmin`\u002F`vmax` across comparable panels. Use `TwoSlopeNorm(vmin=..., vcenter=0, vmax=...)` for a diverging scale centered on zero when values span both sides. Do not rescale each panel independently without communicating it.\n\n**pypalettes** provides curated palettes and Matplotlib colormaps. Prefer a named palette chosen for the data over inventing a multicolor scheme. Use the discrete palette's `.colors` for categorical mappings and a continuous colormap for numeric values:\n\n```python\nfrom pypalettes import load_cmap\n\npalette = load_cmap(\"Acadia\").colors\ncmap = load_cmap(\"BluGrn\", cmap_type=\"continuous\")\npoints = ax.scatter(df[\"x\"], df[\"y\"], c=df[\"value\"], cmap=cmap)\n```\n\n[pypalettes API](https:\u002F\u002Fy-sunflower.github.io\u002Fpypalettes\u002Freference\u002Fload_cmap\u002F) and [palette finder](https:\u002F\u002Fpython-graph-gallery.com\u002Fcolor-palette-finder\u002F). Select a fixed name for reproducible output; avoid a random palette.\n\nFor bubble charts, `scatter(s=...)` encodes marker area in points squared. If bubble area represents magnitude, use `s = scale * values`, not a radius proportional to values. A min\u002Fmax size remapping changes proportional relationships; if needed, communicate that mapping and use it consistently in the size legend. Draw large bubbles first and small bubbles last; use opacity to expose overlap.\n\n## Compose text as part of the chart\n\nPrefer `fig.text()` and `ax.text()` for custom titles, subtitles, direct labels, and notes because their placement is flexible. Use a takeaway title supported by the data, a quieter subtitle for scope and units, and a small source note. Align these blocks with the plotting area or a consistent figure margin. Use a clear size\u002Fweight hierarchy rather than many font families.\n\nChoose coordinates according to what the annotation belongs to:\n\n| Placement | API \u002F transform | Useful for |\n| --- | --- | --- |\n| Data coordinates | `ax.text(x, y, ...)` | End-of-line labels, outliers, extrema |\n| Relative to the panel, 0–1 | `ax.text(..., transform=ax.transAxes)` | Panel names, stable corner notes |\n| Relative to the figure, 0–1 | `fig.text(x, y, ...)` | Shared title, subtitle, caption |\n\nSet `ha` and `va` deliberately. For a label attached to a point, `ax.annotate(..., xytext=(6, 0), textcoords=\"offset points\")` gives a stable physical offset. Use `clip_on=False` when an artist should extend beyond its Axes, and leave enough room in the figure. See the [transforms tutorial](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fusers\u002Fexplain\u002Fartists\u002Ftransforms_tutorial.html) for mixed coordinate systems.\n\nDirectly label a manageable number of lines, bars, or groups near their marks, matching label colors to the data. Reserve space for endpoint labels instead of placing them against the figure edge. Keep a legend when direct labels would crowd the data or when readers need a numeric color or size key. A continuous color scale normally needs a labeled colorbar. Build a manual legend only when its custom layout materially helps.\n\n**highlight_text** handles several colors, weights, or fonts inside one annotation. Use it to turn a title or sentence into a compact color key rather than positioning separate text fragments by eye:\n\n```python\nfrom highlight_text import fig_text\n\nfig_text(\n    x=0.12, y=0.94, s=\"\u003CNorth> grows while \u003CSouth> declines\",\n    highlight_textprops=[{\"color\": \"#335c67\"}, {\"color\": \"#ae2f2f\"}],\n    fig=fig, fontsize=18, ha=\"left\", va=\"top\",\n)\n```\n\nProvide one properties dictionary per `\u003Chighlighted substring>`. `ax_text(..., ax=ax)` uses data coordinates; `fig_text(..., fig=fig)` uses figure coordinates. [highlight_text documentation](https:\u002F\u002Fgithub.com\u002Fznstrider\u002Fhighlight_text#use).\n\n**pyfonts** loads fonts reproducibly as `FontProperties` objects. Prefer the named Google\u002FBunny loaders over searching repositories for font-file URLs. Load the actual weights and styles required by the design; setting `weight=\"bold\"` on text referencing a specific regular font file does not select a different file.\n\n```python\nfrom pyfonts import load_google_font\n\nregular = load_google_font(\"Roboto\")\nbold = load_google_font(\"Roboto\", weight=\"bold\")\nfig.text(0.12, 0.94, \"The supported takeaway\", font=bold, fontsize=20)\nax.text(0.02, 0.95, \"Panel A\", transform=ax.transAxes, font=regular, va=\"top\")\n```\n\nUse `load_font(local_path_or_url)` for an existing font asset; `set_default_font(regular)` applies it to future ticks, labels, and other text. Load fonts before final layout and inspection because font metrics affect spacing. [pyfonts documentation](https:\u002F\u002Fy-sunflower.github.io\u002Fpyfonts\u002F).\n\n**drawarrow** simplifies curved annotation arrows without juggling Matplotlib's several arrow APIs. Use it when a curved connector helps connect a note to a finding; keep its visual weight subordinate to the data:\n\n```python\nfrom drawarrow import ax_arrow\n\nax_arrow(\n    tail_position=(2, 8), head_position=(4, 5),\n    radius=0.25, color=\"#555555\", ax=ax,\n)\n```\n\n`ax_arrow` uses data coordinates; `fig_arrow` is useful for figure-relative connectors. [drawarrow documentation](https:\u002F\u002Fy-sunflower.github.io\u002Fdrawarrow\u002F). For a simple native callout, `ax.annotate()` may already suffice.\n\nFor contextual bands and reference lines, use `ax.axvspan()`, `ax.axhspan()`, `ax.axvline()`, or `ax.axhline()` with subdued styling. For other shapes, add patches with an explicit transform and `zorder`. A decorative arrow or shaded region should explain something specific.\n\n## Use statistical extensions where they reduce work\n\n**Seaborn** supplies grouping and statistical calculations for KDEs, violins, swarms, regression fits, and more. Let it construct the data layer, then finish the composition through Matplotlib. Use axes-level functions when integrating into an existing figure:\n\n```python\nimport seaborn as sns\n\nsns.scatterplot(\n    data=df, x=\"x\", y=\"y\", hue=\"region\", style=\"region\",\n    palette={\"North\": \"#335c67\", \"South\": \"#ae2f2f\"}, ax=ax,\n)\n# A separate distribution example:\n# sns.kdeplot(data=df, x=\"value\", hue=\"region\", fill=True, ax=ax)\n```\n\nCheck statistical defaults before accepting the result: `sns.lineplot()` aggregates repeated x-values and adds confidence intervals by default. Use `estimator=None, errorbar=None` for an already prepared series, and `units=` when distinct trajectories must remain separate. For categorical totals already computed, `ax.barh()` avoids accidental re-aggregation.\n\n`pairplot`, `jointplot`, `relplot`, `displot`, and `catplot` manage their own figures\u002Fgrids; do not treat them as axes-level functions accepting `ax=`. They are useful for exploration, while a manual layout gives more control over a finished explanatory figure. [Seaborn API](https:\u002F\u002Fseaborn.pydata.org\u002Fapi.html), [function overview](https:\u002F\u002Fseaborn.pydata.org\u002Ftutorial\u002Ffunction_overview.html), and [lineplot defaults](https:\u002F\u002Fseaborn.pydata.org\u002Fgenerated\u002Fseaborn.lineplot.html).\n\n## Build layouts around comparisons\n\nUse `plt.subplots()` for regular grids and `plt.subplot_mosaic()` for asymmetric layouts with named panels. Repeated mosaic labels make one Axes span cells; `\".\"` leaves a gap. Prefer these readable layouts before reaching for low-level positioning.\n\n```python\nfig, axs = plt.subplot_mosaic(\n    [[\"main\", \"detail\"], [\"main\", \"distribution\"]],\n    figsize=(10, 6), width_ratios=[2, 1], layout=\"constrained\",\n)\naxs[\"main\"].plot(x, y)\ninset = axs[\"main\"].inset_axes([0.6, 0.12, 0.32, 0.28])\n```\n\nFor small multiples, iterate over groups and axes (`zip(groups, axs.flat)`); `squeeze=False` gives a consistent two-dimensional array even for a single panel. Rank panels intentionally, share axis limits and visual mappings when comparing magnitudes, label each panel inside the Axes, and hide unused panels. Optionally show all other groups as faint background traces in each panel. If scales differ, make that difference conspicuous.\n\nAn inset's bounds are `[left, bottom, width, height]` relative to its parent Axes by default. Use it for a secondary distribution, map detail, compact visual key, or relevant image. For logos\u002Fimages, call `inset.imshow(image)` and `inset.set_axis_off()`; keep the image from competing with the marks. [Mosaic guide](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fusers\u002Fexplain\u002Faxes\u002Fmosaic.html) and [inset API](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fapi\u002F_as_gen\u002Fmatplotlib.axes.Axes.inset_axes.html).\n\n## Treat maps as layered charts with a CRS\n\n**GeoPandas** reads geographic files, joins attributes to geometries, reprojects them, and draws boundaries or choropleths onto a Matplotlib Axes. Start with the geometry table on the left of the join to preserve its geospatial behavior. For one metric per region, validate the join cardinality and inspect unmatched identifiers; show missing values distinctly from zero.\n\n```python\nimport geopandas as gpd\n\nregions = gpd.read_file(\"regions.geojson\")\nmapped = regions.merge(metrics, on=\"region_id\", how=\"left\", validate=\"one_to_one\")\nmapped.plot(\n    column=\"rate\", cmap=\"viridis\", legend=True, ax=ax,\n    edgecolor=\"white\", linewidth=0.4,\n    missing_kwds={\"color\": \"#eeeeee\", \"label\": \"No data\"},\n)\nax.set_axis_off()\n```\n\n[GeoPandas mapping guide](https:\u002F\u002Fgeopandas.org\u002Fen\u002Fstable\u002Fdocs\u002Fuser_guide\u002Fmapping.html).\n\n- Choropleths generally need a rate, proportion, or density; absolute totals often mostly reflect population. When totals are the message, consider proportional symbols instead. Large geographic regions can dominate perception even when few people live there.\n- Use the same color normalization or classification boundaries for maps that readers should compare. Explain the units and any bins; keep missing regions visible.\n- Use `to_crs(...)` to transform coordinates. `set_crs(...)` declares what existing coordinates mean and does not transform them. Choose projections for the task; Mercator is unsuitable for comparing world region areas.\n- For bubble maps, convert longitude\u002Flatitude to point geometries with `gpd.points_from_xy(...)`, assign their known source CRS, and reproject to the map CRS before plotting. Changing the basemap projection alone does not move raw scatter coordinates.\n- For region labels, use projected coordinates for centroid calculations; `representative_point()` is often better when a label must lie inside its region.\n\n**Cartopy** is useful for projection-aware Matplotlib GeoAxes, coastlines, graticules, and global maps. The Axes `projection=` describes the display; each data layer's `transform=` describes its source coordinates. For example, longitude\u002Flatitude points on a Robinson GeoAxes need `ax.scatter(lon, lat, transform=ccrs.PlateCarree(), ...)`. Import projections with `import cartopy.crs as ccrs`. [Cartopy CRS documentation](https:\u002F\u002Fcartopy.readthedocs.io\u002Fstable\u002Freference\u002Fcrs.html). GeoPandas with an appropriate `to_crs()` can suffice when a projected polygon map is all that is needed.\n\n## Reach for specialized tools selectively\n\n**PyWaffle** draws waffle and pictogram charts into an existing Axes. It handles block allocation, spacing, and icons; specify the scale and remember that fitting values into a fixed grid can introduce rounding.\n\n```python\nfrom pywaffle import Waffle\n\nWaffle.make_waffle(ax=ax, rows=5, columns=10, values=[30, 16, 4])\nax.set_aspect(\"equal\")\nax.set_axis_off()\n```\n\n[PyWaffle documentation](https:\u002F\u002Fpywaffle.readthedocs.io\u002Fen\u002Flatest\u002Fquickstart.html). In small multiples, keep the meaning of one block consistent if readers should compare absolute quantities.\n\n**plotnine** offers a grammar-of-graphics interface for layered charts and faceting. Use it when mappings and facets express the chart more clearly than manual Axes loops; `fig = p.draw()` returns a Matplotlib Figure for final annotations or insets. [plotnine documentation](https:\u002F\u002Fplotnine.org\u002F) and [the draw bridge](https:\u002F\u002Fplotnine.org\u002Freference\u002Fggplot.html#draw).\n\n**ninejs** adds hover tooltips, linked highlighting, and click interactions to plotnine charts and exports standalone HTML. Use it when browser interaction is part of the requested deliverable. It works with plotnine objects rather than arbitrary Matplotlib Figures. Consult its [documentation](https:\u002F\u002Fy-sunflower.github.io\u002Fninejs\u002F) for the interaction API supported by the installed version.\n\nFor truly custom curves, use native `matplotlib.path.Path` and `PathPatch`: quadratic Bézier segments use two `CURVE3` entries (control point, endpoint); cubic segments use three `CURVE4` entries (two control points, endpoint). Prefer a dedicated chart library for standard flow diagrams; build paths when the visual design needs custom geometry. See the [Path tutorial](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fusers\u002Fexplain\u002Fartists\u002Fpaths.html). Do not smooth observed time series merely to make them more attractive if the curve would imply unsupported intermediate behavior.\n\n## Inspect the artifact, then refine it\n\nRender and open the exported chart at its intended display size. Check text collisions, clipping, title\u002Fsubtitle spacing, label contrast, line endpoints, legend interpretation, and whether the main comparison is obvious. Refine the actual figure rather than relying on code inspection or successful execution.\n\nSave through `fig.savefig(...)`: PNG for raster delivery, SVG\u002FPDF when vector output is useful. Set DPI for raster output and preserve the intended background with `facecolor=fig.get_facecolor()`. `bbox_inches=\"tight\"` helps include outside annotations but changes the exported bounding dimensions; omit it when exact canvas dimensions are required and fit everything inside the canvas instead.\n\nFor reusable chart pipelines, inspect meaningful artist properties as needed: `fig.axes`, `ax.lines`, `ax.collections`, `ax.patches`, or `ax.get_children()`. Test the intended data and visual contract rather than every styling detail. Colorbars can add Axes, so an Axes count is not automatically a panel count. Artist checks complement visual inspection.\n\nWhen an undocumented-looking keyword is needed, inspect the underlying artist's documentation: `ax.plot()` creates `Line2D` artists, `ax.scatter()` returns a `PathCollection`, and shapes are patches. Their supported properties explain many `**kwargs` in the high-level API. Use the [Axes reference](https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fapi\u002Faxes_api.html) to find the plotting method, then follow its returned artist type for precise styling options.\n",{"name":5,"description":7},"main","22daf3642e9301f3a1af982101767ed879b3d33f",3,"https:\u002F\u002Fgithub.com\u002Fholtzy\u002Fdataviz-skills","https:\u002F\u002Fgithub.com\u002Fholtzy","https:\u002F\u002Fwww.yan-holtz.com","I ❤️ data visualization 🤷🏻‍♂️","2026-11-10 17:00:54",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add holtzy\u002Fdataviz-skills --skill matplotlib",{"tool":38,"command":39},"bunx","bunx skills add holtzy\u002Fdataviz-skills --skill matplotlib",{"tool":41,"command":42},"pnpm","pnpm dlx skills add holtzy\u002Fdataviz-skills --skill matplotlib","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fholtzy\u002Fdataviz-skills\u002Fblob\u002Fmain\u002Fmatplotlib\u002FSKILL.md",true,[46],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"README.md","REFERENCE","参考文档",671,"https:\u002F\u002Fgithub.com\u002Fholtzy\u002Fdataviz-skills\u002Fblob\u002Fmain\u002Fmatplotlib\u002FREADME.md",[53,60,67,74],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M7DBZHNHXJXZDDZ3WA9Z37JZ","new-dataviz-project","Scaffold a new web dataviz project with Yan Holtz's preferred stack - React, TypeScript, D3, shadcn\u002Fui + Tailwind, Lucide icons, Bitter \u002F Roboto \u002F Fira Mono fonts, a narrow reading column, a default barplot, and GitHub Pages deployment. Use when the user asks to create, start, scaffold or set up a new dataviz, chart, D3 or React visualization project or website.","https:\u002F\u002Fgithub.com\u002Fholtzy\u002Fdataviz-skills\u002Fblob\u002Fmain\u002Fnew-dataviz-project\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M7DBYZ73A4RRKBWXCVDBDTKZ","inspiration","Use BEFORE writing any code that draws a chart, map, plot or dashboard (D3, ggplot2, Matplotlib, geopandas, plotly, Vega…), even for a one-line request like \"make a map of X\", \"fais-moi une carte de X\", \"visualise Z\", and even when the work starts with fetching data. Searches curated galleries of published dataviz as one catalog (dataviz-inspiration.com, Dataviz Index) for 3–5 real references to borrow ideas from — form, annotation, palette, layout — with links back to each source. Also use when asked for chart ideas, examples or references, or to improve a chart that looks generic. Triggers: carte, graphique, visualisation, dataviz, infographie, tableau de bord, chart, map, plot, graph, figure, dashboard, choropleth.","https:\u002F\u002Fgithub.com\u002Fholtzy\u002Fdataviz-skills\u002Fblob\u002Fmain\u002Finspiration\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M7DBYTHR58QWTJDJATGBWXHM","ggplot2","Generate, review, or refactor ggplot2 code in R following an opinionated set of best practices. Use whenever the user writes ggplot2 code, asks for ggplot2 help, picks a theme, tweaks scales, sets up faceting, or exports a plot. R-specific.","https:\u002F\u002Fgithub.com\u002Fholtzy\u002Fdataviz-skills\u002Fblob\u002Fmain\u002Fggplot2\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M7DBYNXJJ7VB7NWYVRYRD61J","d3","Use when building, fixing or animating a chart with D3.js inside a React or Next.js app (barplot, scatterplot, line chart, treemap, map…). Covers the D3-for-math \u002F React-for-rendering split, margins and axes, responsiveness with a useDimensions hook, animation with Motion, and switching from SVG to canvas for large datasets. Not for vanilla D3 projects without React.","https:\u002F\u002Fgithub.com\u002Fholtzy\u002Fdataviz-skills\u002Fblob\u002Fmain\u002Fd3\u002FSKILL.md",[],[]]