Synthèse automatique
Guide pratique pour créer, évaluer et peaufiner des visualisations ggplot2 en R, inspiré de l'ouvrage de Kieran Healy sur la visualisation de données.
Points forts
- Couvre l'ensemble du flux ggplot2, de la donnée tidy jusqu'aux thèmes et étiquettes finales
- S'appuie sur des principes de perception visuelle pour justifier le choix du type de graphique et des couleurs
- Inclut des volets spécialisés : visualisation de résultats de modèles, cartes avec sf/statebins, polissage avec patchwork
- Impose la lecture de fichiers de référence ciblés avant de répondre, ce qui structure les conseils
Limites
- Contenu limité à l'écosystème R/ggplot2, sans équivalent Python ou JavaScript
- La licence CC-BY-NC-ND restreint la réutilisation et la redistribution du matériel source
- La description fournie est tronquée : l'inventaire complet des fichiers de référence n'est pas visible
À utiliser dès qu'un utilisateur veut construire, corriger ou améliorer un graphique ggplot2 ou choisir un encodage visuel adapté à ses données.
À éviter pour des visualisations dans d'autres bibliothèques ou langages (matplotlib, D3, Plotly.js) ou pour du tableau de bord interactif, hors périmètre de cette compétence.
Analyse de sécurité
SûrThe skill only uses Read, Edit, Write, Grep, Glob, and R documentation MCP tools. It instructs the agent to create or improve ggplot2 visualizations and consult reference files; there are no destructive commands, network calls, obfuscated payloads, or data exfiltration patterns. The R MCP tools are limited to documentation lookup, not arbitrary code execution beyond typical plotting workflows.
Aucun point d'attention détecté
Comment cette analyse est faiteExemples
Here's my ggplot2 scatterplot of income vs. life expectancy with points colored by region and sized by population — it looks messy. Can you help me clean it up and make it publication-ready?I have categorical survey responses broken down by age group and gender. Which chart type should I use in ggplot2, and how do I avoid misleading my readers?I fit a logistic regression in R and want to plot the predicted probabilities with confidence intervals using ggplot2. How should I structure this?name: socviz description: | Data visualization with ggplot2 based on Kieran Healy's "Data Visualization: A Practical Introduction" (2nd ed., 2026). Use when creating, reviewing, or improving ggplot2 visualizations, choosing appropriate chart types, applying perceptual principles, faceting and grouping data, labeling and annotating plots, visualizing model results, drawing maps, or polishing figures for publication. Covers the grammar of graphics workflow, visual perception, color palettes, layered plot construction, and theme customization. license: CC-BY-NC-ND metadata: source: https://socviz.co author: Kieran Healy edition: 2nd (2026) publisher: Princeton University Press allowed-tools: Read, Edit, Write, Grep, Glob, mcp__r-btw__*
Data Visualization with ggplot2
Based on: Data Visualization: A Practical Introduction (2nd ed.) Author: Kieran Healy (2026). Princeton University Press. Free online: https://socviz.co
Core philosophy
Visualization is a tool for understanding data, not decoration. Every graph encodes data through visual channels (position, length, color, shape) that the human perceptual system decodes with varying accuracy. Good visualization requires understanding both the grammar of graphics and the perceptual system that interprets the output.
The ggplot2 workflow
Every visualization follows the same five steps:
- Tidy data -- Long format: every variable a column, every observation a row
- Mapping --
aes()connects data variables to visual properties (x, y, color, fill, size, shape) - Geom -- Geometric objects render the mapping (points, lines, bars, etc.)
- Scales and coordinates -- Transform axes, set breaks, choose projections
- Labels and guides -- Titles, legends, annotations, themes
p <- ggplot(data = df,
mapping = aes(x = var1, y = var2, color = group))
p + geom_point() +
scale_x_log10(labels = scales::label_comma()) +
labs(x = "X Label", y = "Y Label", title = "Title")
When to use this skill
- User wants to create or improve a ggplot2 visualization
- User asks which chart type to use for their data
- User needs help with faceting, grouping, labeling, or annotating plots
- User wants to visualize model results (coefficients, predictions, residuals)
- User asks about color palettes, themes, or publication-quality figures
- User wants to draw maps with sf or statebins
- User asks about perceptual principles for data visualization
Instructions
-
Classify the request:
- Perceptual/design: Which chart type? What color palette? How to avoid misleading? --> Use
references/perception-principles.md - Building a plot: How to facet, group, layer, label? --> Use the relevant reference file
- Model visualization: Coefficients, predictions, residuals? --> Use
references/model-visualization.md - Maps: Choropleth, cartogram, spatial data? --> Use
references/maps-spatial.md - Polishing: Themes, color, layout, patchwork? --> Use
references/themes-polish.md
- Perceptual/design: Which chart type? What color palette? How to avoid misleading? --> Use
-
Read the relevant reference files before answering
-
Apply these principles in every response:
- Match visual encoding to data type (position for quantitative, color hue for categorical)
- Prefer position on common scale over length, angle, or area
- Use tidy (long-format) data; reshape before plotting if needed
- Build plots layer by layer; inspect at each step
- Distinguish mapping (inside
aes()) from setting (insidegeom_*()) - Calculate summaries with dplyr before graphing when
geom_bar()/stat_count()gets confusing - Use
facet_wrap()orfacet_grid()instead of cramming too much into one panel
-
Follow write-r conventions for all R code (native pipe
|>,.by,join_by(), etc.)
Available resources
Reference files (references/)
| File | Topic | Covers |
|------|-------|--------|
| perception-principles.md | Visual perception and chart choice | Preattentive features, gestalt rules, Cleveland-McGill ranking, color models, honesty/judgment tradeoffs |
| ggplot-fundamentals.md | Core ggplot2 patterns | Tidy data, aes() mapping vs setting, layering geoms, scales, saving plots |
| grouping-faceting.md | Grouped data and faceting | group aesthetic, facet_wrap/facet_grid, stat transformations, histograms, density plots |
| labels-annotations.md | Text, labels, and annotations | Pipes for summarization, text/label geoms, ggrepel, annotate(), scales/guides/themes framework |
| model-visualization.md | Visualizing model results | broom (tidy/augment/glance), coefficient plots, residuals, nested models, survey data, marginal effects |
| maps-spatial.md | Maps and spatial data | sf objects, geom_sf, choropleths, cartograms, statebins, viridis palettes, MAUP |
| themes-polish.md | Polishing and customization | Color palettes, layer-highlight-repeat, theme(), patchwork layouts, workhorses vs show ponies |
Function reference (via MCP, not bundled)
- R: Use
btw_tool_docs_help_page(package_name="ggplot2", topic="<function>")for live docs - R: Use Context7 with library ID for ggplot2 code examples
- Key packages:
ggplot2,scales,ggrepel,patchwork,sf,statebins,broom,colorspace
Quick reference: choosing a geom
| Data situation | Recommended geom | Avoid |
|----------------|------------------|-------|
| Two continuous variables | geom_point() | |
| Continuous + trend | geom_point() + geom_smooth() | |
| One continuous, one categorical | geom_boxplot(), geom_violin(), geom_jitter() | |
| Single continuous distribution | geom_histogram(), geom_density() | |
| Counts of categories | geom_bar() | Pie charts |
| Pre-computed summary | geom_col() or geom_bar(stat = "identity") | |
| Coefficients with CIs | geom_pointrange() | Bar charts for coefficients |
| Time series by group | geom_line(aes(group = ...)) | |
| Trajectories + trend | Gray geom_line() + colored geom_smooth() | |
| Spatial/geographic | geom_sf() | geom_polygon() with map_data (legacy) |
| Two categorical cross-tab | facet_grid(row ~ col) | Stacked bars (except bottom category) |
| Many categories | Horizontal layout (categories on y-axis) | Rotated x-axis labels |
| Labeled points | ggrepel::geom_text_repel() | geom_text() without repulsion |
Key anti-patterns
| Avoid | Do instead | Why |
|-------|-----------|-----|
| Pie charts | Faceted bar charts or dot plots | Angles decoded poorly (Cleveland-McGill) |
| 3D effects | Flat 2D encodings | Perspective distorts values |
| Stacked bars (comparing middle categories) | Faceted bars or Cleveland dot plots | Only bottom category has stable baseline |
| Mapping a string inside aes() | Set property in geom_*() directly | aes(color = "purple") creates unwanted legend |
| geom_bar() for pre-computed data | geom_col() | geom_bar() counts rows by default |
| Default alphabetical ordering | reorder(category, value) | Meaningful order aids comparison |
| Too many channels at once | Facet or simplify | Shape + color + size overwhelms preattentive processing |
| Picking colors ad hoc | Use ColorBrewer, viridis, or colorspace palettes | Perceptually uniform, colorblind-safe |
| + geom_point() on next line | geom_point() + at end of line | ggplot + must end the line, not begin one |
Example: complete workflow
library(tidyverse)
library(scales)
library(ggrepel)
# 1. Summarize data
by_continent <- gapminder |>
summarize(
mean_life = mean(lifeExp),
mean_gdp = mean(gdpPercap),
n_countries = n_distinct(country),
.by = continent
)
# 2. Build plot layer by layer
p <- ggplot(by_continent,
aes(x = mean_gdp, y = mean_life))
p +
geom_point(aes(size = n_countries), alpha = 0.7) +
geom_text_repel(aes(label = continent)) +
scale_x_log10(labels = label_currency()) +
scale_size_continuous(range = c(3, 10)) +
labs(
x = "Mean GDP per Capita",
y = "Mean Life Expectancy (years)",
size = "Countries",
title = "Economic Development and Life Expectancy",
caption = "Source: Gapminder."
) +
theme_minimal() +
theme(legend.position = "bottom")
Best practices
- Always build plots incrementally and inspect at each layer
- Use
ggsave()with explicit dimensions and vector formats (PDF, SVG) for publication - Organize figures in a
figures/subdirectory; usehere::here()for paths - Use
guides(fill = "none")to remove redundant legends - When debugging bizarre output, check the relationship between data structure and aesthetic mappings first
- Prefer faceting over dodging for grouped comparisons
- Place categories on the y-axis when there are many levels
- Order categories by the value being displayed, not alphabetically
- Use
scales::label_*()functions for axis formatting
Du fichier au premier essai
Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.
Consulter la source et ses fichiers annexesCe téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.
1. Télécharger le fichier
Télécharger SKILL.mdDepuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/data-visualization-with-ggplot2-mrwakc5u/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.
Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.
mkdir -p '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/data-visualization-with-ggplot2-mrwakc5u/download' --output '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u/SKILL.md.part' && mv '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u/SKILL.md.part' '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u/SKILL.md'2. Vérifier les prérequis
Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.
Outils déclarés par l’auteur (à vérifier dans votre agent) : Read, Edit, Write, Grep, Glob, mcp__r-btw__*
Extrait original : Quick reference: choosing a geom
| Data situation | Recommended geom | Avoid |
|---|---|---|
| Two continuous variables | geom_point() | |
| Continuous + trend | geom_point() + geom_smooth() | |
| One continuous, one categorical | geom_boxplot(), geom_violin(), geom_jitter() | |
| Single continuous distribution | geom_histogram(), geom_density() | |
| Counts of categories | geom_bar() | Pie charts |
| Pre-computed summary | geom_col() or geom_bar(stat = "identity") | |
| Coefficients with CIs | geom_pointrange() | Bar charts for coefficients |
| Time series by group | geom_line(aes(group = ...)) | |
| Trajectories + trend | Gray geom_line() + colored geom_smooth() | |
| Spatial/geographic | geom_sf() | geom_polygon() with map_data (legacy) |
| Two categorical cross-tab | facet_grid(row ~ col) | Stacked bars (except bottom category) |
| Many categories | Horizontal layout (categories on y-axis) | Rotated x-axis labels |
| Labeled points | ggrepel::geom_text_repel() | geom_text() without repulsion |
Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.
3. Charger la skill
Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.
Claude Code
test -f '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u/SKILL.md' && test -s '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/socviz' && cp -R '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u' '.claude/skills/socviz'Cursor
test -f '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u/SKILL.md' && test -s '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/socviz' && cp -R '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u' '.cursor/skills/socviz'Codex
test -f '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u/SKILL.md' && test -s '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/socviz' && cp -R '.skill-downloads/data-visualization-with-ggplot2-mrwakc5u' '.agents/skills/socviz'OpenSkills
OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.
Installation officielle d’OpenSkillsopenskills install './.skill-downloads/data-visualization-with-ggplot2-mrwakc5u'openskills read 'data-visualization-with-ggplot2-mrwakc5u'La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.
Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.
openskills syncMode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.
4. Faire un premier essai
Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :
Lis .skill-downloads/data-visualization-with-ggplot2-mrwakc5u/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.
Créer des cartes interactives avec kepler.gl
Data & IA
Création de cartes interactives et export HTML autonome avec le package Python keplergl, à partir de données géospatiales (DataFrame, GeoJSON, CSV).
Optimisation de paramètres par agent
Data & IA
Guide d'optimisation de systèmes configurables avec objectif mesurable, via des essais bornés et une recommandation fondée sur des preuves.
Relance des visiteurs ICP
Data & IA
Identifiez les utilisateurs inscrits correspondant au profil client idéal mais qui n'ont pas activé, et rédigez des messages de relance personnalisés pour les réengager.