> ## Documentation Index
> Fetch the complete documentation index at: https://resources.latex-cloud-studio.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Creating Diagrams with TikZ

> Master TikZ for creating professional diagrams in LaTeX. Learn drawing commands, libraries, flowcharts, graphs, and advanced visualization techniques.

export const RenderedOutput = ({title = "Rendered output", ctaHref, ctaLabel = "Open LaTeX Cloud Studio", children}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const trackEditorCta = () => {
    const target = new URL(ctaHref, window.location.href);
    globalThis.posthog?.capture?.("docs_app_cta_clicked", {
      source_page: window.location.pathname,
      source_section: "rendered_output",
      cta_variant: "first_compiled_example",
      target_url: target.toString(),
      target_utm_source: target.searchParams.get("utm_source"),
      target_utm_medium: target.searchParams.get("utm_medium"),
      target_utm_campaign: target.searchParams.get("utm_campaign"),
      target_utm_content: target.searchParams.get("utm_content")
    }, {
      transport: "sendBeacon",
      send_instantly: true
    });
  };
  return <details className="rendered-output" onToggle={event => setIsExpanded(event.currentTarget.open)}>
      <summary className="rendered-output__summary">
        <span className="rendered-output__title">{title}</span>
        <span className="rendered-output__hint" aria-hidden="true">View compiled result</span>
      </summary>
      {isExpanded && <div className="rendered-output__content">
          {children}
          {ctaHref && <aside className="rendered-output__cta" aria-label="Continue in the LaTeX editor">
              <span>
                <strong>Ready to use this syntax?</strong>
                Continue in the browser editor when you want to adapt the example in a real project.
              </span>
              <a href={ctaHref} onClick={trackEditorCta}>{ctaLabel}<span aria-hidden="true"> →</span></a>
            </aside>}
        </div>}
    </details>;
};

export const LatexSource = ({filename, source}) => {
  const [copyStatus, setCopyStatus] = useState("Copy");
  const copySource = async () => {
    try {
      await navigator.clipboard.writeText(source);
      setCopyStatus("Copied");
    } catch {
      setCopyStatus("Select and copy");
    }
  };
  return <figure className="latex-source">
      <figcaption className="latex-source__header">
        <span className="latex-source__filename">{filename}</span>
        <button type="button" className="latex-source__copy" onClick={copySource} aria-live="polite">
          {copyStatus}
        </button>
      </figcaption>
      <pre className="latex-source__pre" aria-label={`LaTeX source: ${filename}`} tabIndex="0">
        <code className="language-latex">{source}</code>
      </pre>
    </figure>;
};

export const LatexPreview = ({src, alt, caption, width, height}) => {
  const minZoom = 1;
  const maxZoom = 3;
  const zoomStep = 0.5;
  const measureSvgContent = async (assetSrc, pageWidth, pageHeight) => {
    const cacheKey = "__latexCloudSvgContentBoxCache";
    const contentBoxCache = globalThis[cacheKey] ?? new Map();
    globalThis[cacheKey] = contentBoxCache;
    if (contentBoxCache.has(assetSrc)) return contentBoxCache.get(assetSrc);
    const measurement = (async () => {
      const assetUrl = new URL(assetSrc, window.location.href);
      if (assetUrl.origin !== window.location.origin) {
        throw new Error("Rendered output must use a same-origin SVG asset.");
      }
      const response = await fetch(assetUrl, {
        credentials: "same-origin"
      });
      if (!response.ok) throw new Error(`Rendered output request failed with ${response.status}.`);
      const source = await response.text();
      const documentNode = new DOMParser().parseFromString(source, "image/svg+xml");
      if (documentNode.querySelector("parsererror")) throw new Error("Rendered output is not valid SVG.");
      const sourceSvg = documentNode.documentElement;
      sourceSvg.querySelectorAll("script, foreignObject").forEach(node => node.remove());
      [sourceSvg, ...sourceSvg.querySelectorAll("*")].forEach(node => {
        [...node.attributes].forEach(attribute => {
          if ((/^on/i).test(attribute.name)) node.removeAttribute(attribute.name);
          if ((attribute.name === "href" || attribute.name === "xlink:href") && !attribute.value.startsWith("#")) {
            node.removeAttribute(attribute.name);
          }
        });
      });
      const measurementHost = document.createElement("div");
      measurementHost.className = "latex-preview__measurement-host";
      const measuredSvg = document.importNode(sourceSvg, true);
      measuredSvg.setAttribute("aria-hidden", "true");
      measurementHost.appendChild(measuredSvg);
      document.body.appendChild(measurementHost);
      try {
        const measuredElements = [...measuredSvg.children].filter(node => !["defs", "desc", "metadata", "style", "title"].includes(node.tagName.toLowerCase()));
        const elementBounds = measuredElements.map(node => node.getBBox()).filter(box => [box.x, box.y, box.width, box.height].every(Number.isFinite) && box.width > 0 && box.height > 0);
        if (elementBounds.length === 0) {
          throw new Error("Rendered output has no measurable visible content.");
        }
        const sortedBounds = [...elementBounds].sort((left, right) => left.y - right.y);
        const clusterGap = pageHeight * 0.045;
        const clusters = [];
        sortedBounds.forEach(box => {
          const current = clusters[clusters.length - 1];
          if (!current || box.y - current.bottom > clusterGap) {
            clusters.push({
              boxes: [box],
              bottom: box.y + box.height
            });
            return;
          }
          current.boxes.push(box);
          current.bottom = Math.max(current.bottom, box.y + box.height);
        });
        const contentClusters = clusters.filter(cluster => {
          const clusterBox = cluster.boxes.reduce((combined, box) => {
            const right = Math.max(combined.x + combined.width, box.x + box.width);
            const bottom = Math.max(combined.y + combined.height, box.y + box.height);
            const x = Math.min(combined.x, box.x);
            const y = Math.min(combined.y, box.y);
            return {
              x,
              y,
              width: right - x,
              height: bottom - y
            };
          });
          const centerY = clusterBox.y + clusterBox.height / 2;
          const isMarginFurniture = cluster.boxes.length <= 2 && clusterBox.width < pageWidth * 0.2 && clusterBox.height < pageHeight * 0.04 && (centerY < pageHeight * 0.08 || centerY > pageHeight * 0.8);
          return !isMarginFurniture;
        });
        const visibleBounds = (contentClusters.length > 0 ? contentClusters : clusters).flatMap(cluster => cluster.boxes);
        const bounds = visibleBounds.reduce((combined, box) => {
          const right = Math.max(combined.x + combined.width, box.x + box.width);
          const bottom = Math.max(combined.y + combined.height, box.y + box.height);
          const x = Math.min(combined.x, box.x);
          const y = Math.min(combined.y, box.y);
          return {
            x,
            y,
            width: right - x,
            height: bottom - y
          };
        });
        const clampValue = (value, minimum, maximum) => Math.min(maximum, Math.max(minimum, value));
        const padding = Math.max(8, Math.min(pageWidth, pageHeight) * 0.025);
        const x = clampValue(bounds.x - padding, 0, pageWidth);
        const y = clampValue(bounds.y - padding, 0, pageHeight);
        const right = clampValue(bounds.x + bounds.width + padding, 0, pageWidth);
        const bottom = clampValue(bounds.y + bounds.height + padding, 0, pageHeight);
        return {
          x,
          y,
          width: right - x,
          height: bottom - y
        };
      } finally {
        measurementHost.remove();
      }
    })();
    contentBoxCache.set(assetSrc, measurement);
    measurement.catch(() => contentBoxCache.delete(assetSrc));
    return measurement;
  };
  const renderPreviewAsset = ({contentBox: assetContentBox, loading}) => {
    if (!assetContentBox) {
      return <img className="latex-preview__asset" src={src} alt={alt} width={width} height={height} loading={loading} draggable="false" />;
    }
    return <svg className="latex-preview__asset" viewBox={`${assetContentBox.x} ${assetContentBox.y} ${assetContentBox.width} ${assetContentBox.height}`} preserveAspectRatio="xMidYMid meet" role="img" aria-label={alt}>
        <image href={src} x="0" y="0" width={width} height={height} />
      </svg>;
  };
  const [isOpen, setIsOpen] = useState(false);
  const [frameMode, setFrameMode] = useState("content");
  const [viewMode, setViewMode] = useState("fit");
  const [zoom, setZoom] = useState(minZoom);
  const [contentBox, setContentBox] = useState(null);
  const [measurementStatus, setMeasurementStatus] = useState("loading");
  const dialogRef = useRef(null);
  const closeButtonRef = useRef(null);
  const viewportRef = useRef(null);
  const previousFocusRef = useRef(null);
  const dragRef = useRef(null);
  useEffect(() => {
    let isCurrent = true;
    setMeasurementStatus("loading");
    measureSvgContent(src, width, height).then(box => {
      if (!isCurrent) return;
      setContentBox(box);
      setMeasurementStatus("ready");
    }).catch(() => {
      if (!isCurrent) return;
      setContentBox(null);
      setFrameMode("page");
      setMeasurementStatus("error");
    });
    return () => {
      isCurrent = false;
    };
  }, [height, src, width]);
  const closeViewer = useCallback(() => {
    setIsOpen(false);
  }, []);
  const openViewer = () => {
    previousFocusRef.current = document.activeElement;
    setFrameMode(contentBox ? "content" : "page");
    setViewMode("fit");
    setZoom(minZoom);
    setIsOpen(true);
  };
  const applyZoom = useCallback(nextZoom => {
    const boundedZoom = Math.min(maxZoom, Math.max(minZoom, nextZoom));
    setViewMode("custom");
    setZoom(boundedZoom);
  }, []);
  const zoomIn = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom + zoomStep : zoom + zoomStep);
  }, [applyZoom, viewMode, zoom]);
  const zoomOut = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom : zoom - zoomStep);
  }, [applyZoom, viewMode, zoom]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    closeButtonRef.current?.focus();
    return () => {
      document.body.style.overflow = previousOverflow;
      previousFocusRef.current?.focus?.();
    };
  }, [isOpen]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const handleKeyDown = event => {
      if (event.key === "Escape") {
        event.preventDefault();
        closeViewer();
        return;
      }
      if ((event.key === "+" || event.key === "=") && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomIn();
        return;
      }
      if (event.key === "-" && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomOut();
        return;
      }
      if (event.key !== "Tab" || !dialogRef.current) return;
      const focusable = [...dialogRef.current.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')];
      if (focusable.length === 0) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [closeViewer, isOpen, zoomIn, zoomOut]);
  const startDrag = event => {
    if (event.button !== 0 || !viewportRef.current) return;
    const viewport = viewportRef.current;
    dragRef.current = {
      pointerId: event.pointerId,
      x: event.clientX,
      y: event.clientY,
      scrollLeft: viewport.scrollLeft,
      scrollTop: viewport.scrollTop
    };
    viewport.setPointerCapture(event.pointerId);
    viewport.dataset.dragging = "true";
  };
  const continueDrag = event => {
    const drag = dragRef.current;
    const viewport = viewportRef.current;
    if (!drag || !viewport || drag.pointerId !== event.pointerId) return;
    viewport.scrollLeft = drag.scrollLeft - (event.clientX - drag.x);
    viewport.scrollTop = drag.scrollTop - (event.clientY - drag.y);
  };
  const stopDrag = event => {
    const viewport = viewportRef.current;
    if (viewport?.hasPointerCapture(event.pointerId)) viewport.releasePointerCapture(event.pointerId);
    if (viewport) delete viewport.dataset.dragging;
    dragRef.current = null;
  };
  const activeContentBox = frameMode === "content" ? contentBox : null;
  const activeWidth = activeContentBox?.width ?? width;
  const activeHeight = activeContentBox?.height ?? height;
  const activeRatio = activeWidth / activeHeight;
  const inlineContentBox = measurementStatus === "ready" ? contentBox : null;
  const inlineWidth = inlineContentBox?.width ?? width;
  const inlineHeight = inlineContentBox?.height ?? height;
  const inlineGeometry = {
    aspectRatio: `${inlineWidth} / ${inlineHeight}`,
    maxWidth: `${30 * inlineWidth / inlineHeight}rem`
  };
  const imageStyle = viewMode === "fit" ? {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: "100%",
    maxWidth: `${Math.max(16, activeRatio * 78)}dvh`
  } : {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: `${zoom * 100}%`,
    maxWidth: "none"
  };
  const zoomLabel = viewMode === "fit" ? frameMode === "content" ? "Fit content" : "Full page" : `${Math.round(zoom * 100)}%`;
  return <figure className="latex-preview">
      <button type="button" className="latex-preview__trigger" onClick={openViewer} aria-haspopup="dialog" aria-label={`Open zoomable preview: ${alt}`}>
        <span className="latex-preview__page" style={inlineGeometry}>
          {measurementStatus === "loading" ? <span className="latex-preview__loading" role="status">Preparing compiled output…</span> : renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: inlineContentBox,
    loading: "lazy"
  })}
        </span>
        <span className="latex-preview__trigger-label" aria-hidden="true">
          <span className="latex-preview__trigger-icon">⌕</span>
          Open viewer
        </span>
      </button>
      <figcaption className="latex-preview__caption">
        <span>
          {caption}
          {measurementStatus === "error" && <span className="latex-preview__status" role="status"> Content fit is unavailable; the complete vector page is shown.</span>}
        </span>
        <a href={src} target="_blank" rel="noreferrer" className="latex-preview__source-link">Open SVG</a>
      </figcaption>

      {isOpen && <div className="latex-preview__backdrop" onMouseDown={event => {
    if (event.target === event.currentTarget) closeViewer();
  }}>
          <section ref={dialogRef} className="latex-preview__dialog" role="dialog" aria-modal="true" aria-label={`Rendered LaTeX viewer: ${alt}`}>
            <header className="latex-preview__toolbar">
              <div className="latex-preview__identity">
                <span className="latex-preview__eyebrow">Compiled LaTeX</span>
                <span className="latex-preview__filename">{alt}</span>
              </div>
              <div className="latex-preview__controls" aria-label="Preview controls">
                <button type="button" className={frameMode === "content" && viewMode === "fit" ? "is-active" : undefined} disabled={!contentBox} onClick={() => {
    setFrameMode("content");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Fit content
                </button>
                <button type="button" className={frameMode === "page" && viewMode === "fit" ? "is-active" : undefined} onClick={() => {
    setFrameMode("page");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Full page
                </button>
                <span className="latex-preview__zoom-group">
                  <button type="button" onClick={zoomOut} disabled={viewMode === "fit" || zoom <= minZoom} aria-label="Zoom out">−</button>
                  <output aria-live="polite" aria-label="Current zoom">{zoomLabel}</output>
                  <button type="button" onClick={zoomIn} disabled={viewMode !== "fit" && zoom >= maxZoom} aria-label="Zoom in">+</button>
                </span>
                <a href={src} target="_blank" rel="noreferrer">Open SVG</a>
                <button ref={closeButtonRef} type="button" className="latex-preview__close" onClick={closeViewer} aria-label="Close rendered LaTeX viewer">
                  Close
                </button>
              </div>
            </header>
            <div ref={viewportRef} className="latex-preview__viewport" data-view-mode={viewMode} onPointerDown={startDrag} onPointerMove={continueDrag} onPointerUp={stopDrag} onPointerCancel={stopDrag}>
              <span className="latex-preview__dialog-page" style={imageStyle}>
                {renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: activeContentBox
  })}
              </span>
            </div>
            <footer className="latex-preview__viewer-note">
              Compiler-generated vector output · Use +/− to zoom · Drag to pan · Esc to close
            </footer>
          </section>
        </div>}
    </figure>;
};

Create publication-quality diagrams directly in LaTeX using TikZ. This comprehensive guide covers basic shapes to complex technical illustrations, including flowcharts, graphs, circuits, and scientific diagrams.

<Info>
  **Prerequisites**: Basic LaTeX knowledge\
  **Time to complete**: 40-45 minutes\
  **Difficulty**: Intermediate to Advanced\
  **What you'll learn**: TikZ syntax, libraries, drawing techniques, and practical examples
</Info>

## Introduction to TikZ

### What is TikZ?

TikZ (TikZ ist kein Zeichenprogramm - TikZ is not a drawing program) is a powerful package for creating graphics programmatically in LaTeX. It provides:

<CardGroup cols={2}>
  <Card title="Precise Control" icon="ruler">
    Exact positioning and measurements
  </Card>

  <Card title="Consistency" icon="palette">
    Matching document fonts and styles
  </Card>

  <Card title="Programmable" icon="code">
    Loops, variables, and calculations
  </Card>

  <Card title="Integration" icon="puzzle-piece">
    Seamless LaTeX integration
  </Card>
</CardGroup>

### Basic Setup

<LatexSource filename="tikz-setup.tex" source={"\\documentclass{article}\n\\usepackage{tikz}\n\n% Load common libraries\n\\usetikzlibrary{\n    arrows.meta,      % Arrow styles\n    positioning,      % Relative positioning\n    shapes.geometric, % Additional shapes\n    calc,            % Coordinate calculations\n    patterns,        % Fill patterns\n    decorations.pathmorphing, % Path decorations\n    backgrounds,     % Background layers\n    fit,            % Fitting nodes\n    chains,         % Chain positioning\n    shadows         % Drop shadows\n}\n\n\\begin{document}\n\n% Inline TikZ\n\\begin{tikzpicture}\n    \\draw (0,0) -- (2,1);\n\\end{tikzpicture}\n\n% Centered figure\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{tikzpicture}\n        % Drawing commands here\n    \\end{tikzpicture}\n    \\caption{TikZ diagram}\n\\end{figure}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output" ctaHref="https://app.latex-cloud-studio.com/?utm_source=resources&utm_medium=rendered_output&utm_campaign=docs_open_app&utm_content=learn_latex_how_to_tikz_diagrams">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-01/page-1.svg" alt="Compiled PDF page 1 from tikz-setup.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

<LatexSource filename="basic-shapes.tex" source={"% Basic shapes and lines\n\\begin{tikzpicture}\n    % Grid for reference (remove in final)\n    \\draw[help lines, gray] (0,0) grid (6,4);\n\n    % Lines\n    \\draw (0,0) -- (2,1);                    % Straight line\n    \\draw[thick] (3,0) -- (5,1);             % Thick line\n    \\draw[dashed] (0,2) -- (2,3);            % Dashed line\n    \\draw[->] (3,2) -- (5,3);                % Arrow\n    \\draw[<->, red] (0,3.5) -- (2,3.5);      % Double arrow\n\n    % Basic shapes\n    \\draw (1,1) circle (0.5);                % Circle\n    \\draw[fill=blue!20] (4,1) circle (0.5);  % Filled circle\n    \\draw (0,0) rectangle (1,0.8);           % Rectangle\n    \\draw[rounded corners] (3,0) rectangle (4,0.8); % Rounded\n\n    % Nodes (shapes with text)\n    \\node[circle, draw] at (1,3) {A};\n    \\node[rectangle, draw, fill=green!20] at (4,3) {Box};\n\\end{tikzpicture}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-02/page-1.svg" alt="Compiled PDF page 1 from basic-shapes.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

## Basic Drawing

### Coordinates and Paths

<LatexSource filename="coordinates.tex" source={"\\begin{tikzpicture}[scale=1.5]\n    % Cartesian coordinates\n    \\draw[->] (-0.5,0) -- (4,0) node[right] {$x$};\n    \\draw[->] (0,-0.5) -- (0,3) node[above] {$y$};\n\n    % Points\n    \\fill (1,1) circle (2pt) node[below] {$(1,1)$};\n    \\fill (3,2) circle (2pt) node[right] {$(3,2)$};\n\n    % Path with multiple segments\n    \\draw[thick, blue] (0,0) -- (1,1) -- (2,0.5) -- (3,2);\n\n    % Curved path\n    \\draw[thick, red] (0,2) .. controls (1,3) and (2,1) .. (3,2.5);\n\n    % Closed path\n    \\draw[thick, green, fill=green!20]\n        (0.5,0.5) -- (1.5,0.5) -- (1,1.5) -- cycle;\n\n    % Polar coordinates\n    \\draw[purple] (0,0) -- (45:2) node[midway, above] {$(45:2)$};\n\n    % Relative coordinates\n    \\draw[orange, thick] (2,1) -- ++(1,0.5) -- ++(0.5,-0.5);\n\\end{tikzpicture}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-03/page-1.svg" alt="Compiled PDF page 1 from coordinates.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

<LatexSource filename="path-operations.tex" source={"\\begin{tikzpicture}[scale=1.2]\n    % Different path operations\n\n    % Straight lines with corners\n    \\draw[blue] (0,0) -| (2,1);  % Horizontal then vertical\n    \\draw[red] (3,0) |- (5,1);   % Vertical then horizontal\n\n    % Bezier curves\n    \\draw[thick] (0,2) .. controls (1,3) .. (2,2);\n    \\draw[thick, green] (3,2) .. controls (3.5,3) and (4.5,3) .. (5,2);\n\n    % Arcs\n    \\draw[thick, orange] (1,3) arc (0:90:1);\n    \\draw[thick, purple] (4,3) arc (180:45:1.5);\n\n    % Smooth curves through points\n    \\draw[thick, brown] plot[smooth] coordinates {\n        (0,4) (0.5,4.5) (1,4.2) (1.5,4.8) (2,4.3)\n    };\n\n    % Cycle back to start\n    \\draw[thick, cyan, fill=cyan!20]\n        (3,4) -- (4,4.5) -- (5,4) -- (4,3.5) -- cycle;\n\\end{tikzpicture}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-04/page-1.svg" alt="Compiled PDF page 1 from path-operations.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

### Nodes and Labels

<LatexSource filename="nodes-basics.tex" source={"\\begin{tikzpicture}[\n    every node/.style={font=\\sffamily},\n    main node/.style={circle, draw, minimum size=1cm}\n]\n    % Basic nodes\n    \\node (A) at (0,0) {Simple text};\n    \\node[draw] (B) at (3,0) {Boxed text};\n    \\node[circle, draw] (C) at (6,0) {Circle};\n\n    % Styled nodes\n    \\node[main node, fill=blue!20] (D) at (0,2) {D};\n    \\node[rectangle, draw, rounded corners, fill=red!20] (E) at (3,2) {Rect};\n    \\node[ellipse, draw, fill=green!20] (F) at (6,2) {Ellipse};\n\n    % Node connections\n    \\draw[->] (A) -- (B);\n    \\draw[->] (B) -- (C);\n    \\draw[<->, thick] (D) -- (E);\n    \\draw[->, dashed] (E) -- (F);\n\n    % Labels on edges\n    \\draw[->] (D) -- (A) node[midway, left] {edge};\n    \\draw[->] (F) -- (C) node[near start, right] {label};\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

<LatexSource filename="node-positioning.tex" source={"\\begin{tikzpicture}[\n    node distance=2cm,\n    box/.style={rectangle, draw, minimum width=2cm, minimum height=1cm}\n]\n    % Central node\n    \\node[box, fill=yellow!30] (center) {Center};\n\n    % Relative positioning\n    \\node[box, above=of center] (top) {Above};\n    \\node[box, below=of center] (bottom) {Below};\n    \\node[box, left=of center] (left) {Left};\n    \\node[box, right=of center] (right) {Right};\n\n    % Diagonal positioning\n    \\node[box, above right=of center] (tr) {Top Right};\n    \\node[box, below left=of center] (bl) {Bottom Left};\n\n    % Custom distances\n    \\node[box, above=3cm of center] (far) {Far Above};\n    \\node[box, right=1cm of center] (near) {Near Right};\n\n    % Connect all to center\n    \\foreach \\n in {top, bottom, left, right, tr, bl, far, near}\n        \\draw[->] (center) -- (\\n);\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

## Flowcharts and Diagrams

### Basic Flowcharts

<LatexSource filename="simple-flowchart.tex" source={"\\begin{tikzpicture}[\n    node distance=2cm,\n    startstop/.style={rectangle, rounded corners, draw, fill=red!30, minimum width=3cm, minimum height=1cm},\n    process/.style={rectangle, draw, fill=blue!30, minimum width=3cm, minimum height=1cm},\n    decision/.style={diamond, draw, fill=green!30, minimum width=3cm, minimum height=1cm, aspect=2},\n    io/.style={trapezium, trapezium left angle=70, trapezium right angle=110, draw, fill=yellow!30, minimum width=3cm, minimum height=1cm},\n    arrow/.style={thick, ->, >=stealth}\n]\n    % Nodes\n    \\node[startstop] (start) {Start};\n    \\node[io, below=of start] (input) {Input data};\n    \\node[process, below=of input] (process1) {Process data};\n    \\node[decision, below=of process1] (decision) {Valid?};\n    \\node[process, below=of decision] (process2) {Generate output};\n    \\node[startstop, below=of process2] (stop) {End};\n\n    % Alternative path\n    \\node[process, right=3cm of decision] (error) {Handle error};\n\n    % Connections\n    \\draw[arrow] (start) -- (input);\n    \\draw[arrow] (input) -- (process1);\n    \\draw[arrow] (process1) -- (decision);\n    \\draw[arrow] (decision) -- node[left] {Yes} (process2);\n    \\draw[arrow] (decision) -- node[above] {No} (error);\n    \\draw[arrow] (error) |- (input);\n    \\draw[arrow] (process2) -- (stop);\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

<LatexSource filename="complex-flowchart.tex" source={"\\begin{tikzpicture}[\n    node distance=1.5cm and 2cm,\n    box/.style={rectangle, draw, fill=#1, minimum width=2.5cm, minimum height=0.8cm, font=\\small},\n    decision/.style={diamond, draw, fill=orange!30, aspect=1.5, font=\\small},\n    cloud/.style={cloud, draw, fill=gray!20, minimum width=2cm, minimum height=1cm},\n    database/.style={cylinder, draw, fill=purple!30, minimum width=2cm, minimum height=1cm, shape border rotate=90},\n    arr/.style={->, >=latex, thick}\n]\n    % System architecture flowchart\n    \\node[cloud] (user) {User};\n    \\node[box=blue!30, below=of user] (ui) {UI Layer};\n    \\node[box=green!30, below=of ui] (api) {API Gateway};\n    \\node[decision, below=of api] (auth) {Authenticated?};\n    \\node[box=yellow!30, below left=of auth] (login) {Login Service};\n    \\node[box=cyan!30, below right=of auth] (service) {Business Logic};\n    \\node[database, below=of service] (db) {Database};\n    \\node[box=red!30, right=of service] (cache) {Cache};\n\n    % Connections with labels\n    \\draw[arr] (user) -- (ui);\n    \\draw[arr] (ui) -- (api) node[midway, right] {HTTP};\n    \\draw[arr] (api) -- (auth);\n    \\draw[arr] (auth) -- node[left] {No} (login);\n    \\draw[arr] (auth) -- node[right] {Yes} (service);\n    \\draw[arr] (login) -| (api);\n    \\draw[arr] (service) -- (db) node[midway, right] {Query};\n    \\draw[arr, <->] (service) -- (cache) node[midway, above] {Read/Write};\n    \\draw[arr] (db) -| (cache) node[near start, left] {Update};\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

### State Diagrams

<LatexSource filename="state-diagram.tex" source={"\\begin{tikzpicture}[\n    >=stealth,\n    node distance=3cm,\n    state/.style={circle, draw, minimum size=1.5cm, font=\\small},\n    initial/.style={state, fill=green!30},\n    final/.style={state, double, fill=red!30},\n    transition/.style={->, thick}\n]\n    % States\n    \\node[initial] (idle) {Idle};\n    \\node[state, right=of idle] (loading) {Loading};\n    \\node[state, right=of loading] (active) {Active};\n    \\node[state, below=of active] (error) {Error};\n    \\node[final, below=of idle] (terminated) {Done};\n\n    % Transitions\n    \\draw[transition] (idle) -- node[above] {start} (loading);\n    \\draw[transition] (loading) -- node[above] {success} (active);\n    \\draw[transition] (loading) -- node[right] {fail} (error);\n    \\draw[transition] (active) -- node[right] {complete} (terminated);\n    \\draw[transition] (error) -- node[below] {retry} (loading);\n    \\draw[transition] (error) -- node[left] {abort} (terminated);\n    \\draw[transition, bend left=30] (active) to node[above] {reset} (idle);\n\n    % Self loop\n    \\draw[transition] (active) to[loop above] node {update} (active);\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

<LatexSource filename="automaton.tex" source={"\\begin{tikzpicture}[\n    shorten >=1pt,\n    node distance=2.5cm,\n    on grid,\n    auto,\n    state/.style={circle, draw, minimum size=1.2cm},\n    accepting/.style={state, double}\n]\n    % Finite automaton\n    \\node[state, initial] (q0) {$q_0$};\n    \\node[state] (q1) [right=of q0] {$q_1$};\n    \\node[state] (q2) [right=of q1] {$q_2$};\n    \\node[accepting] (q3) [right=of q2] {$q_3$};\n\n    % Transitions\n    \\path[->]\n        (q0) edge node {0} (q1)\n        (q0) edge[loop above] node {1} (q0)\n        (q1) edge node {1} (q2)\n        (q1) edge[bend left] node {0} (q0)\n        (q2) edge node {0} (q3)\n        (q2) edge[bend left] node[below] {1} (q1)\n        (q3) edge[loop above] node {0,1} (q3);\n\n    % Label\n    \\node[below=2cm of q1, text width=6cm, align=center] {\n        Finite automaton accepting strings with exactly three 0s\n    };\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

## Graphs and Trees

### Graph Structures

<LatexSource filename="simple-graph.tex" source={"\\begin{tikzpicture}[\n    node distance=2cm,\n    vertex/.style={circle, draw, fill=blue!20, minimum size=8mm},\n    edge/.style={thick}\n]\n    % Vertices\n    \\node[vertex] (A) {A};\n    \\node[vertex, right=of A] (B) {B};\n    \\node[vertex, below right=of A] (C) {C};\n    \\node[vertex, below left=of A] (D) {D};\n    \\node[vertex, below=of C] (E) {E};\n\n    % Edges\n    \\draw[edge] (A) -- (B);\n    \\draw[edge] (A) -- (C);\n    \\draw[edge] (A) -- (D);\n    \\draw[edge] (B) -- (C);\n    \\draw[edge] (C) -- (D);\n    \\draw[edge] (C) -- (E);\n    \\draw[edge] (D) -- (E);\n\n    % Edge labels\n    \\draw[edge] (B) -- node[above right] {5} (E);\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

<LatexSource filename="directed-graph.tex" source={"\\begin{tikzpicture}[\n    scale=1.5,\n    vertex/.style={circle, draw, fill=orange!30, minimum size=10mm, font=\\footnotesize},\n    edge/.style={->, >=stealth, thick},\n    weight/.style={midway, font=\\scriptsize, fill=white, inner sep=1pt}\n]\n    % Weighted directed graph\n    \\node[vertex] (1) at (0,2) {1};\n    \\node[vertex] (2) at (2,3) {2};\n    \\node[vertex] (3) at (4,2) {3};\n    \\node[vertex] (4) at (3,0) {4};\n    \\node[vertex] (5) at (1,0) {5};\n\n    % Weighted edges\n    \\draw[edge] (1) -- node[weight] {3} (2);\n    \\draw[edge] (2) -- node[weight] {1} (3);\n    \\draw[edge] (3) -- node[weight] {4} (4);\n    \\draw[edge] (4) -- node[weight] {2} (5);\n    \\draw[edge] (5) -- node[weight] {6} (1);\n    \\draw[edge] (1) -- node[weight] {5} (3);\n    \\draw[edge] (2) -- node[weight] {2} (4);\n\n    % Self loop\n    \\draw[edge] (3) to[loop right] node[weight] {1} (3);\n\\end{tikzpicture}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-12/page-1.svg" alt="Compiled PDF page 1 from directed-graph.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

### Tree Structures

<LatexSource filename="binary-tree.tex" source={"\\begin{tikzpicture}[\n    level distance=1.5cm,\n    level 1/.style={sibling distance=4cm},\n    level 2/.style={sibling distance=2cm},\n    level 3/.style={sibling distance=1cm},\n    treenode/.style={circle, draw, fill=green!30, minimum size=8mm},\n    edge from parent/.style={draw, ->, >=stealth}\n]\n    % Binary tree\n    \\node[treenode] {8}\n        child {\n            node[treenode] {3}\n            child {\n                node[treenode] {1}\n            }\n            child {\n                node[treenode] {6}\n                child {\n                    node[treenode] {4}\n                }\n                child {\n                    node[treenode] {7}\n                }\n            }\n        }\n        child {\n            node[treenode] {10}\n            child[missing] {}\n            child {\n                node[treenode] {14}\n                child {\n                    node[treenode] {13}\n                }\n                child[missing] {}\n            }\n        };\n\\end{tikzpicture}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-13/page-1.svg" alt="Compiled PDF page 1 from binary-tree.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

<LatexSource filename="tree-layouts.tex" source={"\\begin{tikzpicture}[\n    grow=down,\n    level 1/.style={sibling distance=5cm},\n    level 2/.style={sibling distance=2.5cm},\n    level 3/.style={sibling distance=1.5cm},\n    edge from parent/.style={draw, thick},\n    nodeStyle/.style={rectangle, draw, fill=cyan!20, minimum width=2cm, minimum height=0.8cm, font=\\small},\n    leafStyle/.style={nodeStyle, fill=yellow!30}\n]\n    % Organizational chart style tree\n    \\node[nodeStyle] {CEO}\n        child {\n            node[nodeStyle] {CTO}\n            child {\n                node[nodeStyle] {Dev Team}\n                child { node[leafStyle] {Frontend} }\n                child { node[leafStyle] {Backend} }\n            }\n            child {\n                node[nodeStyle] {DevOps}\n                child { node[leafStyle] {Cloud} }\n                child { node[leafStyle] {Security} }\n            }\n        }\n        child {\n            node[nodeStyle] {CFO}\n            child { node[leafStyle] {Accounting} }\n            child { node[leafStyle] {Finance} }\n        }\n        child {\n            node[nodeStyle] {CMO}\n            child { node[leafStyle] {Marketing} }\n            child { node[leafStyle] {Sales} }\n        };\n\n    % Alternative: horizontal tree\n    \\begin{scope}[xshift=10cm]\n        \\tikzset{\n            grow=right,\n            level 1/.style={sibling distance=2cm, level distance=2.5cm},\n            level 2/.style={sibling distance=1cm, level distance=2.5cm}\n        }\n        \\node[nodeStyle] {Root}\n            child {\n                node[nodeStyle] {A}\n                child { node[leafStyle] {A1} }\n                child { node[leafStyle] {A2} }\n            }\n            child {\n                node[nodeStyle] {B}\n                child { node[leafStyle] {B1} }\n            };\n    \\end{scope}\n\\end{tikzpicture}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-14/page-1.svg" alt="Compiled PDF page 1 from tree-layouts.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

## Scientific Diagrams

### Mathematical Diagrams

<LatexSource filename="function-plot.tex" source={"\\begin{tikzpicture}[scale=1.5]\n    % Axes\n    \\draw[->] (-0.5,0) -- (4,0) node[right] {$x$};\n    \\draw[->] (0,-0.5) -- (0,3) node[above] {$y$};\n\n    % Grid\n    \\draw[gray, very thin] (0,0) grid (3.5,2.5);\n\n    % Function plots\n    \\draw[blue, thick, domain=0:3.5, samples=100]\n        plot (\\x, {0.5*\\x*\\x - \\x + 1});\n    \\draw[red, thick, domain=0:3.5, samples=100]\n        plot (\\x, {sin(\\x r) + 1});\n    \\draw[green, thick, domain=0.1:3.5, samples=100]\n        plot (\\x, {ln(\\x) + 1});\n\n    % Labels\n    \\node[blue] at (3,2.2) {$f(x) = \\frac{1}{2}x^2 - x + 1$};\n    \\node[red] at (2,0.3) {$g(x) = \\sin(x) + 1$};\n    \\node[green] at (3.2,1.3) {$h(x) = \\ln(x) + 1$};\n\n    % Points of interest\n    \\fill[blue] (2,1) circle (2pt) node[above right] {$(2,1)$};\n\\end{tikzpicture}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-15/page-1.svg" alt="Compiled PDF page 1 from function-plot.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

<LatexSource filename="geometric-diagram.tex" source={"\\begin{tikzpicture}[scale=2]\n    % Triangle with labels\n    \\coordinate[label=left:$A$] (A) at (0,0);\n    \\coordinate[label=right:$B$] (B) at (3,0);\n    \\coordinate[label=above:$C$] (C) at (1.5,2);\n\n    % Draw triangle\n    \\draw[thick] (A) -- (B) -- (C) -- cycle;\n\n    % Angles\n    \\draw[fill=red!20] (A) -- (0.5,0) arc (0:53.13:0.5) -- cycle;\n    \\draw[fill=blue!20] (B) -- (2.5,0) arc (180:126.87:0.5) -- cycle;\n    \\draw[fill=green!20] (C) -- (1.5,1.5) arc (270:270-73.74:0.5) -- cycle;\n\n    % Angle labels\n    \\node at (0.7,0.2) {$\\alpha$};\n    \\node at (2.3,0.2) {$\\beta$};\n    \\node at (1.5,1.6) {$\\gamma$};\n\n    % Side labels\n    \\node[below] at (1.5,0) {$c$};\n    \\node[above right] at (2.25,1) {$a$};\n    \\node[above left] at (0.75,1) {$b$};\n\n    % Height\n    \\draw[dashed] (C) -- (1.5,0) node[midway, right] {$h$};\n    \\fill (1.5,0) circle (1pt);\n\\end{tikzpicture}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-16/page-1.svg" alt="Compiled PDF page 1 from geometric-diagram.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

### Physics Diagrams

<LatexSource filename="physics-diagram.tex" source={"\\begin{tikzpicture}[\n    force/.style={->, thick, blue},\n    mass/.style={rectangle, draw, fill=gray!30, minimum width=1.5cm, minimum height=1.5cm}\n]\n    % Free body diagram\n    \\node[mass] (m) {$m$};\n\n    % Forces\n    \\draw[force] (m.north) -- ++(0,2) node[above] {$N$};\n    \\draw[force] (m.south) -- ++(0,-2) node[below] {$mg$};\n    \\draw[force] (m.east) -- ++(1.5,0) node[right] {$F$};\n    \\draw[force] (m.west) -- ++(-1,0) node[left] {$f$};\n\n    % Surface\n    \\draw[thick] (-3,-0.75) -- (3,-0.75);\n    \\foreach \\x in {-3,-2.5,...,3} {\n        \\draw (\\x,-0.75) -- (\\x-0.25,-1);\n    }\n\n    % Angle for inclined plane\n    \\begin{scope}[xshift=6cm]\n        \\draw[thick] (0,0) -- (4,0) -- (4,2) -- cycle;\n        \\node[mass, rotate=26.57] at (2.5,1.25) {$m$};\n        \\draw[force] (2.5,1.25) -- ++(0,-2) node[below] {$mg$};\n        \\draw[force, rotate=26.57] (2.5,1.25) -- ++(0,1.5) node[above] {$N$};\n        \\node at (0.5,0.15) {$\\theta$};\n    \\end{scope}\n\\end{tikzpicture}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-17/page-1.svg" alt="Compiled PDF page 1 from physics-diagram.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

<LatexSource filename="circuit-diagram.tex" source={"\\begin{tikzpicture}[circuit ee IEC]\n    % Simple circuit\n    \\draw (0,0) to[battery] (0,3)\n          to[ammeter] (3,3)\n          to[resistor={info=$R_1$}] (3,1.5)\n          to[resistor={info=$R_2$}] (3,0)\n          -- (0,0);\n\n    % Parallel circuit\n    \\begin{scope}[xshift=5cm]\n        \\draw (0,0) to[voltage source] (0,3) -- (1,3)\n              to[resistor={info=$R_1$}] (3,3) -- (4,3)\n              -- (4,0) -- (0,0);\n        \\draw (1,3) -- (1,2)\n              to[resistor={info=$R_2$}] (3,2) -- (3,3);\n        \\draw (1,2) -- (1,1)\n              to[capacitor={info=$C$}] (3,1) -- (3,2);\n    \\end{scope}\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

## Advanced Techniques

### Loops and Automation

<LatexSource filename="foreach-loops.tex" source={"\\begin{tikzpicture}\n    % Grid of nodes using foreach\n    \\foreach \\x in {0,1,2,3,4} {\n        \\foreach \\y in {0,1,2,3} {\n            \\node[circle, draw, fill=blue!\\x0!green!\\y0]\n                at (\\x,\\y) {\\tiny \\x,\\y};\n        }\n    }\n\n    % Radial pattern\n    \\begin{scope}[xshift=7cm, yshift=2cm]\n        \\foreach \\angle in {0,30,...,330} {\n            \\draw[thick, color=red!\\angle!blue]\n                (0,0) -- (\\angle:2);\n            \\fill[color=red!\\angle!blue]\n                (\\angle:2) circle (2pt);\n        }\n    \\end{scope}\n\n    % Connected graph\n    \\begin{scope}[yshift=-5cm]\n        \\foreach \\i in {1,...,6} {\n            \\node[circle, draw, fill=orange!30]\n                (n\\i) at ({360/6 * (\\i-1)}:2) {\\i};\n        }\n        \\foreach \\i in {1,...,6} {\n            \\foreach \\j in {\\i,...,6} {\n                \\draw[gray] (n\\i) -- (n\\j);\n            }\n        }\n    \\end{scope}\n\\end{tikzpicture}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-19/page-1.svg" alt="Compiled PDF page 1 from foreach-loops.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

<LatexSource filename="calculations.tex" source={"\\begin{tikzpicture}\n    % Using calculations\n    \\coordinate (A) at (0,0);\n    \\coordinate (B) at (4,0);\n    \\coordinate (C) at (2,3);\n\n    % Midpoints\n    \\coordinate (MAB) at ($(A)!0.5!(B)$);\n    \\coordinate (MBC) at ($(B)!0.5!(C)$);\n    \\coordinate (MCA) at ($(C)!0.5!(A)$);\n\n    % Draw triangle and medians\n    \\draw[thick] (A) -- (B) -- (C) -- cycle;\n    \\draw[dashed, red] (A) -- (MBC);\n    \\draw[dashed, red] (B) -- (MCA);\n    \\draw[dashed, red] (C) -- (MAB);\n\n    % Centroid (intersection of medians)\n    \\coordinate (G) at (barycentric cs:A=1,B=1,C=1);\n    \\fill[red] (G) circle (2pt) node[below] {$G$};\n\n    % Perpendicular lines\n    \\draw[blue, thick] (A) -- ($(B)!(A)!(C)$);\n\n    % Circle through three points\n    \\node[draw, circle through=(A)(B)(C)] {};\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

### Styles and Scopes

<LatexSource filename="custom-styles.tex" source={"\\begin{tikzpicture}[\n    % Define custom styles\n    my node/.style={\n        circle,\n        draw=#1,\n        fill=#1!20,\n        minimum size=1cm,\n        font=\\bfseries\n    },\n    my edge/.style={\n        thick,\n        ->,\n        >=stealth,\n        #1\n    },\n    important/.style={\n        my node=red,\n        drop shadow\n    },\n    normal/.style={\n        my node=blue\n    }\n]\n    % Use custom styles\n    \\node[important] (A) at (0,0) {A};\n    \\node[normal] (B) at (3,0) {B};\n    \\node[normal] (C) at (3,3) {C};\n    \\node[important] (D) at (0,3) {D};\n\n    % Styled edges\n    \\draw[my edge={red, dashed}] (A) -- (B);\n    \\draw[my edge={blue}] (B) -- (C);\n    \\draw[my edge={green, bend left}] (C) -- (D);\n    \\draw[my edge={orange, bend right}] (D) -- (A);\n\n    % Scope with different settings\n    \\begin{scope}[xshift=6cm, scale=0.8, opacity=0.7]\n        \\node[my node=purple] (E) at (0,0) {E};\n        \\node[my node=cyan] (F) at (2,2) {F};\n        \\draw[my edge={thick}] (E) -- (F);\n    \\end{scope}\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

<LatexSource filename="layers.tex" source={"\\begin{tikzpicture}\n    % Background layer\n    \\begin{pgfonlayer}{background}\n        \\fill[yellow!20] (-1,-1) rectangle (5,4);\n        \\fill[blue!20] (1,0.5) circle (2);\n    \\end{pgfonlayer}\n\n    % Main layer\n    \\draw[thick] (0,0) grid (4,3);\n    \\node[circle, draw, fill=white] at (2,1.5) {Main};\n\n    % Foreground layer\n    \\begin{pgfonlayer}{foreground}\n        \\node[rectangle, draw, fill=red!70, opacity=0.8] at (3,2) {Front};\n    \\end{pgfonlayer}\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

### Decorations and Patterns

<LatexSource filename="decorations.tex" source={"\\begin{tikzpicture}[\n    decoration={\n        snake,\n        amplitude=.5mm,\n        segment length=3mm\n    }\n]\n    % Different decorations\n    \\draw[decorate, thick] (0,0) -- (3,0) node[right] {snake};\n\n    \\draw[\n        decoration={coil, segment length=4mm},\n        decorate, thick\n    ] (0,1) -- (3,1) node[right] {coil};\n\n    \\draw[\n        decoration={zigzag, segment length=4mm},\n        decorate, thick\n    ] (0,2) -- (3,2) node[right] {zigzag};\n\n    \\draw[\n        decoration={random steps, segment length=3mm},\n        decorate, thick\n    ] (0,3) -- (3,3) node[right] {random};\n\n    % Text along path\n    \\draw[\n        decoration={\n            text along path,\n            text={This text follows the curve!}\n        },\n        decorate\n    ] (5,0) .. controls (6,2) and (7,2) .. (8,0);\n\n    % Arrow decorations\n    \\draw[\n        thick,\n        decoration={\n            markings,\n            mark=at position 0.25 with {\\arrow{>}},\n            mark=at position 0.5 with {\\arrow{>}},\n            mark=at position 0.75 with {\\arrow{>}}\n        },\n        postaction={decorate}\n    ] (5,3) circle (1);\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

<LatexSource filename="patterns-fills.tex" source={"\\begin{tikzpicture}\n    % Pattern fills\n    \\fill[pattern=horizontal lines] (0,0) rectangle (2,1);\n    \\fill[pattern=vertical lines] (2.5,0) rectangle (4.5,1);\n    \\fill[pattern=north east lines] (5,0) rectangle (7,1);\n    \\fill[pattern=grid] (7.5,0) rectangle (9.5,1);\n\n    % Custom patterns\n    \\fill[pattern=dots] (0,2) rectangle (2,3);\n    \\fill[pattern=crosshatch] (2.5,2) rectangle (4.5,3);\n    \\fill[pattern=fivepointed stars] (5,2) rectangle (7,3);\n    \\fill[pattern=bricks] (7.5,2) rectangle (9.5,3);\n\n    % Combining patterns and colors\n    \\fill[pattern=north west lines, pattern color=blue]\n        (0,4) rectangle (2,5);\n    \\fill[pattern=checkerboard, pattern color=red]\n        (2.5,4) rectangle (4.5,5);\n\n    % Gradient fills\n    \\shade[left color=red, right color=blue] (5,4) rectangle (7,5);\n    \\shade[inner color=yellow, outer color=orange] (7.5,4) circle (0.5);\n\\end{tikzpicture}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

## Best Practices

### Optimization Tips

<Tip>
  **TikZ best practices**:

  1. **Use styles** - Define reusable styles for consistency
  2. **Name nodes** - Makes connections easier
  3. **Use calculations** - Let TikZ compute positions
  4. **Layer wisely** - Background, main, foreground
  5. **Externalize** - Compile complex diagrams separately
  6. **Comment code** - Especially for complex diagrams
  7. **Use libraries** - Don't reinvent the wheel
  8. **Test incrementally** - Build diagrams step by step
</Tip>

### Common Pitfalls

<Warning>
  **Avoid these TikZ mistakes**:

  1. **Hardcoded positions** - Use relative positioning
  2. **Repeated code** - Use loops and styles
  3. **Complex paths** - Break into smaller parts
  4. **Missing libraries** - Load required libraries
  5. **Scale issues** - Test at final size
  6. **Memory problems** - Externalize large diagrams
  7. **Forgotten semicolons** - Every command needs one
</Warning>

## Complete Examples

### Network Diagram

<LatexSource filename="network-diagram.tex" source={"\\documentclass{article}\n\\usepackage{tikz}\n\\usetikzlibrary{positioning, shapes.geometric, shadows, backgrounds}\n\n\\begin{document}\n\n\\begin{tikzpicture}[\n    node distance=2cm,\n    server/.style={\n        rectangle, draw, fill=blue!20,\n        minimum width=2cm, minimum height=1.5cm,\n        drop shadow, font=\\small\n    },\n    client/.style={\n        rectangle, draw, fill=green!20,\n        minimum width=1.5cm, minimum height=1cm,\n        drop shadow, font=\\small\n    },\n    database/.style={\n        cylinder, draw, fill=orange!20,\n        minimum width=2cm, minimum height=1.5cm,\n        shape border rotate=90,\n        drop shadow, font=\\small\n    },\n    cloud/.style={\n        cloud, draw, fill=gray!20,\n        minimum width=3cm, minimum height=2cm,\n        drop shadow, font=\\small\n    },\n    connection/.style={thick, ->, >=stealth},\n    label/.style={font=\\footnotesize, fill=white, inner sep=2pt}\n]\n    % Core components\n    \\node[cloud] (internet) {Internet};\n    \\node[server, below=3cm of internet] (loadbalancer) {Load Balancer};\n\n    % Web servers\n    \\node[server, below left=2cm and 1cm of loadbalancer] (web1) {Web Server 1};\n    \\node[server, below right=2cm and 1cm of loadbalancer] (web2) {Web Server 2};\n\n    % Application servers\n    \\node[server, below=of web1] (app1) {App Server 1};\n    \\node[server, below=of web2] (app2) {App Server 2};\n\n    % Databases\n    \\node[database, below right=2cm and 0cm of app1] (db1) {Primary DB};\n    \\node[database, right=1cm of db1] (db2) {Replica DB};\n\n    % Clients\n    \\node[client, left=3cm of internet] (client1) {Client 1};\n    \\node[client, above left=1cm and 2cm of internet] (client2) {Client 2};\n    \\node[client, above right=1cm and 2cm of internet] (client3) {Client 3};\n\n    % Connections\n    \\draw[connection] (client1) -- (internet);\n    \\draw[connection] (client2) -- (internet);\n    \\draw[connection] (client3) -- (internet);\n\n    \\draw[connection, <->] (internet) -- node[label] {HTTPS} (loadbalancer);\n\n    \\draw[connection] (loadbalancer) -- (web1);\n    \\draw[connection] (loadbalancer) -- (web2);\n\n    \\draw[connection] (web1) -- (app1);\n    \\draw[connection] (web2) -- (app2);\n\n    \\draw[connection] (app1) -- (db1);\n    \\draw[connection] (app2) -- (db1);\n    \\draw[connection, <->] (db1) -- node[label] {Sync} (db2);\n\n    % Background regions\n    \\begin{pgfonlayer}{background}\n        \\fill[yellow!20, rounded corners]\n            ([shift={(-0.5,0.5)}]loadbalancer.north west)\n            rectangle\n            ([shift={(0.5,-0.5)}]db2.south east);\n        \\node[above] at (loadbalancer.north) {Data Center};\n    \\end{pgfonlayer}\n\\end{tikzpicture}\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

### Data Flow Diagram

<LatexSource filename="data-flow-diagram.tex" source={"\\documentclass{article}\n\\usepackage{tikz}\n\\usetikzlibrary{arrows.meta, positioning, shapes, decorations.pathmorphing}\n\n\\begin{document}\n\n\\begin{tikzpicture}[\n    >=latex,\n    node distance=2.5cm,\n    process/.style={\n        rectangle, draw, fill=blue!30,\n        minimum width=3cm, minimum height=1cm,\n        rounded corners, font=\\small\\sffamily\n    },\n    data/.style={\n        trapezium, draw, fill=green!30,\n        trapezium left angle=70,\n        trapezium right angle=110,\n        minimum width=2.5cm, minimum height=0.8cm,\n        font=\\small\\sffamily\n    },\n    storage/.style={\n        rectangle, draw, fill=orange!30,\n        minimum width=2.5cm, minimum height=0.8cm,\n        path picture={\n            \\draw ([xshift=0.1cm]path picture bounding box.north west)\n                -- ([xshift=-0.1cm]path picture bounding box.north east);\n        },\n        font=\\small\\sffamily\n    },\n    flow/.style={thick, ->, >=stealth},\n    label/.style={font=\\footnotesize, above, sloped}\n]\n    % Input layer\n    \\node[data] (input) {Raw Data};\n\n    % Processing pipeline\n    \\node[process, below=of input] (validate) {Validate};\n    \\node[process, below=of validate] (transform) {Transform};\n    \\node[process, below=of transform] (analyze) {Analyze};\n\n    % Storage\n    \\node[storage, right=3cm of validate] (raw) {Raw Storage};\n    \\node[storage, right=3cm of transform] (processed) {Processed DB};\n    \\node[storage, right=3cm of analyze] (results) {Results Cache};\n\n    % Output\n    \\node[data, below=of analyze] (output) {Reports};\n    \\node[process, right=of output] (visualize) {Visualize};\n    \\node[data, right=of visualize] (dashboard) {Dashboard};\n\n    % Main flow\n    \\draw[flow] (input) -- node[label] {Stream} (validate);\n    \\draw[flow] (validate) -- node[label] {Valid} (transform);\n    \\draw[flow] (transform) -- node[label] {Clean} (analyze);\n    \\draw[flow] (analyze) -- node[label] {Insights} (output);\n\n    % Storage connections\n    \\draw[flow, dashed] (validate) -- node[label] {Archive} (raw);\n    \\draw[flow, dashed] (transform) -- node[label] {Store} (processed);\n    \\draw[flow, dashed] (analyze) -- node[label] {Cache} (results);\n\n    % Visualization flow\n    \\draw[flow] (output) -- (visualize);\n    \\draw[flow] (visualize) -- (dashboard);\n    \\draw[flow, bend right] (results) to node[label, below] {Query} (visualize);\n\n    % Error handling\n    \\node[process, left=2cm of transform, fill=red!30] (error) {Error Handler};\n    \\draw[flow, red, bend right] (validate) to node[label, below] {Invalid} (error);\n    \\draw[flow, red, bend right] (transform) to node[label, below] {Failed} (error);\n    \\draw[flow, red] (error) |- (input);\n\n    % Decorations\n    \\node[above=0.5cm of input, font=\\large\\bfseries] {Data Processing Pipeline};\n\n    % Legend\n    \\begin{scope}[xshift=8cm, yshift=-3cm]\n        \\node[process, minimum width=2cm] (l1) at (0,0) {Process};\n        \\node[data, minimum width=2cm] (l2) at (0,-1) {Data};\n        \\node[storage, minimum width=2cm] (l3) at (0,-2) {Storage};\n        \\draw[flow] (3,0) -- node[above] {Flow} (4.5,0);\n        \\draw[flow, dashed] (3,-1) -- node[above] {Store} (4.5,-1);\n        \\node[above=0.3cm of l1, font=\\bfseries] {Legend};\n    \\end{scope}\n\\end{tikzpicture}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-tikz-diagrams-26/page-1.svg" alt="Compiled PDF page 1 from data-flow-diagram.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

## Next Steps

Explore more LaTeX visualization:

<CardGroup cols={2}>
  <Card title="Mathematics" icon="chart-line" href="/learn/latex/mathematics/basics">
    Mathematical equations and graphs
  </Card>

  <Card title="Circuit Diagrams" icon="microchip" href="/learn/latex/specialized-notation/circuits">
    Electronic circuit drawings
  </Card>

  <Card title="Chemical Structures" icon="atom" href="/learn/latex/specialized-notation/chemistry">
    Molecular diagrams
  </Card>

  <Card title="Physics Notation" icon="cube" href="/learn/latex/specialized-notation/physics">
    Physics diagrams and notation
  </Card>
</CardGroup>

***

<Info>
  **Pro tip**: Start simple and build complexity gradually. Use the TikZ manual (texdoc tikz) as your reference - it's comprehensive with excellent examples. Consider externalizing complex diagrams to speed up compilation of your main document.
</Info>
