Логотип D3

D3

Спільнота
holtzy
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 / 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.

Огляд

Видавецьholtzy
Репозиторійdataviz-skills
Назва навичкиd3
Зірки
207
Форки
10
Файли в пакеті
3
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 3

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Видавець на GitHub: holtzy. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ D3 у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/holtzy/dataviz-skills/tree/main/d3
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/holtzy/dataviz-skills.git /tmp/dataviz-skills
mkdir -p .claude/skills
cp -r /tmp/dataviz-skills/d3 .claude/skills/d3
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку D3 в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку D3, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка D3 не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

D3 + React

Build charts where D3 does the math and React does the rendering. Every chart follows the same skeleton: compute with D3, render JSX.

1. D3 for math only

D3 modules split in two families:

  • Math (use them): d3-scale, d3-shape, d3-array, d3-hierarchy, d3-geo, d3-force, d3-interpolate, d3-format, d3-time-format… Numbers in, numbers or path strings out.
  • Rendering (don't use them): d3-selection, d3-transition. No d3.select(), .append(), .attr(), .data().join() or .transition().

React renders every element in JSX and loops with .map():

jsx
const xScale = d3.scaleLinear().domain([0, d3.max(data, (d) => d.value)]).range([0, boundsWidth]);

return data.map((d) => (
  <rect key={d.id} x={0} y={yScale(d.name)} width={xScale(d.value)} height={yScale.bandwidth()} />
));

For a path, call the D3 generator and pass the string to d:

jsx
const linePath = d3.line().x((d) => xScale(d.x)).y((d) => yScale(d.y))(data);
return <path d={linePath} fill="none" stroke="currentColor" />;

When adapting an online D3 example, keep its math and rewrite its select/append/attr chain as JSX. import * as d3 from "d3" is fine; importing single modules (import { scaleLinear } from "d3-scale") only matters for strict bundle-size goals.

2. Margins and translation

Leave room for the axes with a MARGIN object, compute the bounds dimensions, and shift everything into the bounds with a single translate:

jsx
const MARGIN = { top: 10, right: 30, bottom: 50, left: 30 };

const boundsWidth = width - MARGIN.right - MARGIN.left;
const boundsHeight = height - MARGIN.top - MARGIN.bottom;

return (
  <svg width={width} height={height}>
    <g transform={`translate(${MARGIN.left}, ${MARGIN.top})`}>
      {/* every shape and axis goes here, in bounds coordinates */}
    </g>
  </svg>
);
  • Scales map to the bounds: .range([0, boundsWidth]) and .range([boundsHeight, 0]).
  • Don't bake margins into the scale range (.range([MARGIN.left, width - MARGIN.right])). It is common in D3 examples, but margin math then leaks into every scale, axis and shape.

3. Axes are React components

Draw axes in JSX with scale.ticks(), and size the tick count from the available pixels rather than a fixed number:

jsx
const TICK_LENGTH = 6;

export const AxisBottom = ({ xScale, pixelsPerTick }) => {
  const range = xScale.range();
  const numberOfTicksTarget = Math.floor((range[1] - range[0]) / pixelsPerTick);

  return (
    <>
      <line x1={range[0]} x2={range[1]} stroke="currentColor" />
      {xScale.ticks(numberOfTicksTarget).map((value) => (
        <g key={value} transform={`translate(${xScale(value)}, 0)`}>
          <line y2={TICK_LENGTH} stroke="currentColor" />
          <text style={{ fontSize: "10px", textAnchor: "middle", transform: "translateY(20px)" }}>{value}</text>
        </g>
      ))}
    </>
  );
};

// Inside the bounds <g>: push the axis to the bottom
<g transform={`translate(0, ${boundsHeight})`}>
  <AxisBottom xScale={xScale} pixelsPerTick={60} />
</g>

AxisLeft is the same with y and textAnchor: "end". d3.axisBottom() called inside a useEffect on a ref is an accepted fallback, and the only place D3 touches the DOM.

4. Responsiveness: useDimensions + wrapper

Never hardcode width and height. Every chart gets:

  1. One shared hook, useDimensions, in the project's hook folder (hook/use-dimensions.ts, or the existing hooks/ folder). It measures a div and updates on resize. Write it once, following the contract in references/responsiveness.md, and import it in every chart.
  2. A non-responsive chart component that takes width and height as props.
  3. A responsive wrapper that measures its div and forwards the size plus all other props. The wrapper does nothing else:
jsx
// Responsive component = wrapper that manages the dimensions and does nothing else
export const ResponsiveBarplot = (props) => {
  const chartRef = useRef(null);

  const chartSize = useDimensions(chartRef);

  return (
    <div ref={chartRef} style={{ width: '100%', height: '100%' }}>
      <Barplot
        height={chartSize.height}
        width={chartSize.width}
        {...props} // pass all the props
      />
    </div>
  );
};

// Non responsive component
const Barplot = ({ width, height, data }) => {
  //... dataviz code goes here
}

Parents render <ResponsiveBarplot data={data} /> inside a container with an explicit height. The chart returns null while width or height is 0 (first render). Read references/responsiveness.md for the hook contract, the TypeScript wrapper, and the pitfalls (zero height, flex children, resize performance).

5. SVG by default, canvas for performance

Use SVG by default: declarative JSX, CSS, and event handlers on every shape.

Switch the marks to canvas when the DOM gets too heavy: thousands of marks (large scatterplots, dense heatmaps, big networks), many charts on one page, or hover effects that update every mark. Keep axes, labels and tooltips in SVG/HTML layered on top. Read references/canvas.md before writing canvas code (layering, sharp rendering on retina screens, hover detection).

6. Animation with Motion

Animate only change that matters: a dataset switch, or feedback on a user interaction. Don't animate the first render or anything that isn't changing. Keep it short: 80–150 ms for hover, 200–400 ms for transitions in tools, up to ~1 s in one-shot storytelling.

  • Small effects (hover color, tooltip fade): a plain CSS transition.
  • Marks moving, entering or leaving: spring animations with Motion (npm install motion, import { motion, AnimatePresence } from "motion/react"). Not d3.transition, which fights React for the DOM. framer-motion is the old name of the same library.
jsx
<motion.rect
  key={d.id}                       // stable id from the data, never the array index
  animate={{ y: yScale(d.name), width: xScale(d.value) }}
  transition={{ type: "spring", stiffness: 100, damping: 18 }}
/>

Read references/animation.md for enter/exit with AnimatePresence, path morphing, line drawing, and reduced motion.

Checklist

  • No d3.select, .append, .attr or d3.transition: D3 computes, JSX renders.
  • MARGIN object, boundsWidth / boundsHeight, one translate on the bounds <g>.
  • Axes as React components using scale.ticks() and pixelsPerTick.
  • Chart takes width / height props, exported through a Responsive* wrapper using the shared useDimensions hook.
  • Early return null when width or height is 0.
  • key is a stable id from the data, not the index.
  • SVG unless the mark count calls for canvas.
  • Animation only on data change or interaction, with Motion springs.

Want to go further? These conventions come from the D3 Loves React course, with hundreds of examples in the React Graph Gallery.

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ 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 / 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.

Навіщо використовувати D3 у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. D3 — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити D3 у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/holtzy/dataviz-skills/tree/main/d3. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати D3?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати D3?

Зі скількома забажаєте. У TypingMind ви можете використовувати D3 із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ D3?

Так. На GitHub цю навичку публікує holtzy за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇