Skip to main content
v2026.11,986 entries · CC-BY 4.0

ggiraph: Interactive ggplot2 Graphics in R

ggiraph extends ggplot2 to produce interactive SVG charts in R with tooltips, click actions, linked selections, and seamless Shiny web integration.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

The ggiraph package in R extends the standard building and styling ggplot2 graphics workflow by compiling visualizations into dynamic, interactive Scalable Vector Graphics (SVG) with hover tooltips, click actions, linked animations, and bidirectional Shiny event listeners.

Developed by David Gohel and Panagiotis Skintzos, ggiraph operates as an htmlwidget that bridges static exploratory data analysis and responsive web delivery. Unlike translation libraries that convert ggplot structures into external JavaScript schemas, ggiraph relies on an internal C++ rendering device (dsvg) to convert native grid graphical objects (grobs) directly into an interactive SVG Document Object Model (DOM). This architecture ensures that complex custom themes, mathematical annotations, multi-panel facet grids, and exact typography authored in R remain visually identical to static print figures while adding user interactivity.

What it is used for in research

In academic and clinical research, static charts frequently struggle to convey dense, high-dimensional datasets without visual clutter. Researchers working with genomic variant callouts, longitudinal patient cohorts, multi-site ecological surveys, and econometric microdata often face an uncomfortable compromise between summarization and granularity. Embedding interactive capabilities directly into publication-quality figures resolves this challenge by allowing readers to inspect individual data points on demand.

Researchers use ggiraph primarily across three core scientific computing workflows:

  • Exploratory Data Inspection: Inspecting high-density scatter plots, volcano plots, and Manhattan plots where thousands of individual data points conceal critical outliers. By mapping identifying variables to hover tooltips, investigators can immediately reveal sample IDs, p-values, fold changes, or accession numbers without cluttering the visualization space with static text labels. This approach integrates naturally alongside techniques for non-overlapping label placement with ggrepel to balance static readability with dynamic exploratory depth.
  • Interactive Scientific Dissemination: Publishing dynamic research artifacts in reproducible HTML reports, Quarto documents, and online journal supplementary materials. Because ggiraph produces self-contained HTML widgets, readers can explore data tables and figures locally in their web browsers without requiring a running R server or proprietary visualization software. This open architecture reinforces computational reproducibility by preserving the underlying data mappings and R rendering pipelines in executable analysis notebooks.
  • Bidirectional Analytic Dashboards: Building interactive decision-support applications in R Shiny. ggiraph exposes native selection mechanisms where clicking or brushing points, bars, or map polygons updates reactive server-side inputs. For instance, an investigator can click a cluster of outliers on a principal component analysis (PCA) plot to immediately filter downstream demographic tables, survival curves, or differential expression summaries in real time.

Because ggiraph is licensed under GPL-3 as open source software, it integrates directly into institutional and grant-funded analytical environments without per-seat licensing fees or proprietary cloud vendor lock-in. Researchers maintain full ownership of their data pipelines, visual styling, and hosting infrastructure.

How to install or access it

The ggiraph package is distributed officially through the Comprehensive R Archive Network (CRAN). It requires an active installation of R (version 4.0.0 or higher recommended) and depends on the gdtools, systemfonts, and Rcpp packages for low-level font metrics and C++ compilation.

CRAN Installation

To install the current stable release of ggiraph directly from your designated CRAN mirror, execute the following command in your R console or RStudio environment:

install.packages("ggiraph")

This command automatically identifies and installs required runtime dependencies, including ggplot2 (version 4.0.0 or higher), htmlwidgets, htmltools, systemfonts, and gdtools. If you are operating on a headless Linux computing cluster or Docker container, ensure that the underlying operating system provides the necessary font rendering and image compression development headers (specifically libpng-dev and fontconfig libraries) before compiling from source.

Verifying Package Installation and Dependencies

After installation completes, verify that the package loads correctly and inspect the installed version using standard R session management commands:

library(ggiraph)
packageVersion("ggiraph")

The package version should report 0.9.6 or later. To confirm that your graphics environment can generate interactive SVG objects, you can check that the package’s primary interactive geometry functions and its core htmlwidget wrapper function, girafe(), are accessible in the namespace:

exists("girafe", where = "package:ggiraph")
exists("geom_point_interactive", where = "package:ggiraph")

Both checks should return TRUE, confirming that the rendering engine and interactive grammar extensions are ready for data processing.

Step-by-step instructions

Creating an interactive visualization with ggiraph follows a structured four-step task workflow: preparing research data with formatted tooltip strings, constructing a ggplot object using interactive geometries, rendering the widget through girafe() with customized behavioral options, and connecting selection inputs in a Shiny application.

Step 1: Loading Required Libraries and Preparing Experimental Data

Begin by loading ggiraph alongside ggplot2 and dplyr. When assembling tooltip text, raw data values should be explicitly formatted and sanitized. The ggiraph rendering engine parses tooltip content as HTML, meaning multi-line text must use HTML line break tags (such as
) and special characters must be properly escaped to avoid breaking SVG attribute strings.

library(ggplot2)
library(ggiraph)
library(dplyr)
library(htmltools)

# Assemble sample biomedical research dataset
set.seed(42)
cohort_data <- data.frame(
  patient_id = sprintf("PT-%04d", 1:40),
  biomarker_baseline = round(rnorm(40, mean = 50, sd = 10), 1),
  treatment_response = round(rnorm(40, mean = 75, sd = 15), 1),
  cohort_group = rep(c("Control", "Low-Dose", "High-Dose", "Combination"), each = 10),
  adverse_event = sample(c("None", "Mild", "Moderate"), 40, replace = TRUE, prob = c(0.7, 0.2, 0.1))
)

# Format explicit HTML tooltips and unique selection keys
cohort_data %
  mutate(
    tooltip_text = paste0(
      "Patient: ", htmlEscape(patient_id), "
", "Cohort: ", htmlEscape(cohort_group), "
", "Baseline: ", biomarker_baseline, " ng/mL
", "Response: ", treatment_response, " %
", "Adverse Event: ", htmlEscape(adverse_event) ), data_key = patient_id )

Step 2: Constructing the Interactive Plot Object

In standard ggplot2 code, geometric layers are added using functions such as geom_point(), geom_col(), or geom_line(). In ggiraph, you substitute these with their interactive counterparts by appending the suffix _interactive. Inside the aes() mapping function, assign your formatted text to the tooltip aesthetic and your unique identifier to the data_id aesthetic.

# Construct publication-styled ggplot with interactive points
p <- ggplot(cohort_data, aes(x = biomarker_baseline, y = treatment_response, color = cohort_group)) +
  geom_point_interactive(
    aes(
      tooltip = tooltip_text,
      data_id = data_key
    ),
    size = 3.5,
    alpha = 0.85
  ) +
  geom_smooth(method = "lm", se = FALSE, linetype = "dashed", color = "#4a5568") +
  scale_color_brewer(palette = "Set1") +
  labs(
    title = "Biomarker Baseline vs. Treatment Response",
    subtitle = "Hover over patient markers to view clinical metrics; click to select",
    x = "Baseline Concentration (ng/mL)",
    y = "Treatment Response (% Change)",
    color = "Treatment Group"
  ) +
  theme_minimal(base_size = 13) +
  theme(
    legend.position = "bottom",
    plot.title = element_text(face = "bold", size = 15),
    panel.grid.minor = element_blank()
  )

When applying visual styles, researchers can incorporate advanced styling techniques outlined in our guide on customizing ggplot2 themes to maintain institutional typography and color consistency across all static and interactive figures.

Step 3: Rendering the Interactive Widget with girafe() Options

To render the ggplot object into an interactive SVG widget, pass the plot to girafe(). Behavioral options such as tooltip styling, hover highlights, selection modes, and zoom parameters are defined using helper functions passed to the options argument list.

# Render interactive widget with customized behavior and styling
widget <- girafe(
  ggobj = p,
  width_svg = 8,
  height_svg = 6,
  options = list(
    opts_tooltip(
      css = "background-color:#1a202c;color:#ffffff;padding:8px 12px;border-radius:6px;font-size:12px;font-family:sans-serif;box-shadow:0 4px 6px rgba(0,0,0,0.15);",
      opacity = 0.95,
      delay_mouseover = 150,
      delay_mouseout = 300,
      zindex = 9999
    ),
    opts_hover(
      css = "fill:#e53e3e;stroke:#9b2c2c;stroke-width:2.5px;cursor:pointer;"
    ),
    opts_hover_inv(
      css = "opacity:0.25;"
    ),
    opts_selection(
      type = "multiple",
      css = "stroke:#2b6cb0;stroke-width:3px;fill:#3182ce;"
    ),
    opts_zoom(
      min = 0.75,
      max = 3.0
    ),
    opts_toolbar(
      position = "topright",
      saveaspng = TRUE
    )
  )
)

# Display widget in RStudio Viewer or knit to HTML document
widget

Notice the use of opts_hover_inv(css = "opacity:0.25;"): when a user hovers over an individual patient data point, all non-hovered points fade into the background. Furthermore, if multiple geometries across facets or layers share the same data_id, hovering over one element simultaneously highlights all associated elements across the visualization.

Step 4: Embedding in Shiny with Bidirectional Reactive Inputs

To integrate the interactive plot into an R Shiny dashboard, define a placeholder in the user interface (UI) with girafeOutput() and bind the rendering logic in the server function with renderGirafe(). User selections on the plot automatically populate a reactive Shiny input vector named input$clinical_scatter_selected.

library(shiny)

ui <- fluidPage(
  titlePanel("Clinical Cohort Explorer"),
  sidebarLayout(
    sidebarPanel(
      h4("Selected Cohort Records"),
      p("Click data points on the scatter plot to inspect detailed clinical profiles."),
      tableOutput("selected_patient_table"),
      actionButton("reset_selection", "Clear Selections", class = "btn-secondary")
    ),
    mainPanel(
      girafeOutput("clinical_scatter", width = "100%", height = "550px")
    )
  )
)

server <- function(input, output, session) {
  
  output$clinical_scatter <- renderGirafe({
    girafe(
      ggobj = p,
      width_svg = 8,
      height_svg = 5.5,
      options = list(
        opts_selection(
          type = "multiple",
          css = "stroke:#2b6cb0;stroke-width:3px;fill:#3182ce;"
        ),
        opts_hover(css = "fill:#e53e3e;cursor:pointer;")
      )
    )
  })
  
  # Reactive table showing data for points selected by the user
  output$selected_patient_table <- renderTable({
    selected_ids %
      filter(patient_id %in% selected_ids) %>%
      select(patient_id, cohort_group, biomarker_baseline, treatment_response, adverse_event)
  })
  
  # Observer to reset selections programmatically
  observeEvent(input$reset_selection, {
    session$sendCustomMessage(
      type = "clinical_scatter_set",
      message = character(0)
    )
  })
}

# Run Shiny application
shinyApp(ui, server)

Output and how to read it

Understanding how ggiraph renders its output requires distinguishing between its visual SVG representation in the client browser and its data structures on the Shiny server.

Visual SVG DOM Structure

When girafe() executes, the C++ dsvg graphics device intercepts ggplot2’s graphical rendering tree and writes an XML-based SVG element directly into the web page. Unlike static PNG or raster outputs, every data element—such as a circle, rectangle, or path—is represented as an individual SVG node (for example circle, rect, or path tags) adorned with custom HTML data attributes:

  • title or data-tooltip: Encapsulates the formatted HTML string provided to the tooltip aesthetic, which the JavaScript runtime extracts and positions inside a floating div when the mouse enters the bounding box.
  • data-id: Encapsulates the identifier provided to the data_id aesthetic. The JavaScript event listener uses this attribute to query all matching DOM nodes across the graphic and apply the CSS styling rules defined in opts_hover() and opts_selection().
  • onclick: Contains the evaluated JavaScript callback expression if an action was defined, allowing automated link navigation or external modal triggers upon mouse click.

Because the visual representation is pure SVG, scaling or zooming the plot in a web browser preserves crisp vector geometry without pixelation or resolution degradation. Researchers inspecting high-dpi figures or dense geospatial charts can zoom into sub-regions while retaining pin-sharp typography and marker boundaries.

Reading Shiny Reactive Selection Inputs

Inside an active Shiny session, user interactions produce reactive values that follow a predictable naming convention based on the output ID specified in girafeOutput():

  • input$[outputId]_selected: Returns a character vector containing the data_id values of all currently selected geometric elements. If no elements are selected, the value evaluates to NULL (or an empty character vector depending on initialization). In single-selection mode (opts_selection(type = "single")), this vector contains at most one element. In multiple-selection mode (opts_selection(type = "multiple")), it aggregates all clicked or lasso-selected keys.
  • input$[outputId]_hovered: If hover reactivity is explicitly enabled via opts_hover(reactive = TRUE), this input captures the data_id of the element currently positioned under the mouse cursor, allowing real-time cross-filtering during mouse movement.
  • input$[outputId]_key_selected and input$[outputId]_theme_selected: Capture user interactions with interactive legend keys or custom theme components when interactive guide elements are configured.

When filtering data frames based on input$[outputId]_selected, always verify that the input is non-null and non-empty using req() or an explicit conditional check to prevent downstream evaluation errors during initial application loading.

Troubleshooting

When integrating interactive SVG graphics into complex research dashboards and reports, developers occasionally encounter styling conflicts, clipping bugs, or reactive event disconnects. The following solutions address the most common technical hurdles.

1. Tooltip Hidden Under Modals or Sidebars (Z-Index Conflict)

In modern web frameworks such as Bootstrap, Shiny modal dialogs (modalDialog()), and absolute floating panels, the container elements often carry high CSS z-index values (for example 1050 or 2000). By default, ggiraph tooltips render at a lower stacking index, causing the popup box to appear trapped behind sidebar cards or completely obscured beneath dialog backdrops.

Solution: Explicitly configure the zindex parameter inside opts_tooltip() to a high value that supersedes outer framework containers:

opts_tooltip(
  css = "background-color:#2d3748;color:#ffffff;padding:8px;",
  zindex = 9999
)

2. Custom CSS Ignored or Malformed

Passing multi-line CSS blocks or complex selectors with nested braces into opts_hover() or opts_tooltip() will cause styles to fail silently. ggiraph parses the css argument as an inline CSS declaration string that is applied directly to the element’s style attribute.

Solution: Format CSS rules strictly as a semicolon-separated string of property-value pairs without selector prefixes or curly braces. If you wish to disable hover color overrides entirely and retain the geometry’s original fill color, supply an empty string: opts_hover(css = "").

3. Microscopic Plots or Blank Vertical Whitespace in Responsive Layouts

When rendering a girafe plot inside responsive containers, CSS grid systems, or Quarto HTML pages, the graphic may collapse into a tiny postage-stamp size or generate massive vertical gaps underneath the plot area. This behavior stems from competing constraints between the fixed aspect ratio of the underlying SVG and the dynamic dimensions of the parent HTML container.

Solution: Ensure responsive container scaling is activated in girafe() using opts_sizing(rescale = TRUE), and set appropriate width and height properties in girafeOutput():

# In the UI definition:
girafeOutput("plot_id", width = "100%", height = "auto")

# In the server render call:
girafe(
  ggobj = p,
  width_svg = 7,
  height_svg = 5,
  options = list(opts_sizing(rescale = TRUE))
)

For modern dashboard layouts built with the bslib package and card containers, setting both dimensions to NULL (for example, girafeOutput("plot_id", width = NULL, height = NULL)) enables bslib’s flexbox filling mechanics to manage widget resizing smoothly.

4. Click Selections Not Triggering Shiny Reactivity

If clicking points or bars on the plot does not update input$[outputId]_selected, verify that two prerequisites are met. First, the interactive geometry layer must have an explicit data_id aesthetic mapped to a valid data column. Second, opts_selection() must not be configured with type = "none". If only_shiny = FALSE is set, selection highlighting occurs locally in the browser without requiring a server roundtrip, but Shiny server inputs will still update if the connection is active.

Free alternatives

While ggiraph provides high fidelity for ggplot2 users, several other open-source visualization packages cater to different analytical and architectural requirements in R. The decision table below compares free, actively maintained alternatives across primary research use cases, rendering engines, and learning curves.

Package Primary Research Use Case Rendering Architecture ggplot2 Transition Curve Licensing Model
ggiraph Preserving exact ggplot2 themes, typography, and grobs while adding tooltips and Shiny selection Interactive SVG via C++ dsvg graphics device Zero learning curve (replaces standard geoms with geom_*_interactive) GPL-3 (Free and open source)
plotly High-speed 3D surface plots, WebGL scatter arrays, and rapid prototype charts HTML5 Canvas, WebGL, and SVG via Plotly.js Low to moderate (supports ggplotly conversion, but complex themes require adjustments) MIT (Free and open source)
echarts4r High-performance interactive dashboards, financial charts, and rich streaming visual widgets HTML5 Canvas and SVG via Apache ECharts Moderate (uses dedicated pipe syntax, no direct ggplot2 grob translation) Apache-2.0 (Free and open source)
rbokeh Interactive pan/zoom exploratory charts and interactive geospatial tiled maps HTML5 Canvas via BokehJS Moderate (uses custom figure composition syntax) MIT (Free and open source)
lattice Static multi-panel trellis graphics for experimental and factorial designs Standard R base/grid graphics system Independent formula-based paradigm (static output only, no web interactivity) GPL-2 / GPL-3 (Free and open source)

For research teams deciding between packages, the choice typically hinges on whether preserving ggplot2 code structure is paramount. Teams with existing, heavily customized ggplot2 pipelines benefit most from ggiraph because it requires changing only geometry function names and adding interactive aesthetics. Conversely, researchers seeking out-of-the-box 3D surface mapping or large WebGL point clouds may prefer the standalone capabilities outlined in our Plotly in R guide. The comprehensive data table below compares interactive R graphics packages across graphics engines, licensing, and Shiny reactivity parameters.

Frequently asked questions

How does ggiraph differ from plotly’s ggplotly function in R?

The fundamental distinction lies in rendering architecture. The ggplotly() function in the plotly package translates R’s internal ggplot2 object into a JavaScript JSON dictionary matching the Plotly.js declarative schema. During this translation, intricate ggplot2 formatting—such as custom font families, specialized facet strip alignments, subtle theme borders, and grob annotations—is frequently distorted or lost. In contrast, ggiraph compiles ggplot2 grobs directly into an interactive Scalable Vector Graphic (SVG) using its internal C++ dsvg graphics device. This preserves 100% of the original ggplot2 visual styling, line widths, and theme typography while embedding interactive data attributes directly into the SVG DOM elements.

Can ggiraph interactive plots be exported to static PDF or Word manuscripts?

ggiraph widgets are designed primarily for HTML-based interactive runtimes, such as web browsers, Quarto HTML reports, R Markdown documents, and Shiny applications. When compiling documents to static formats like PDF or Microsoft Word via knitr, the interactive elements (tooltips and hover scripts) cannot execute. However, ggiraph provides a toolbar button (enabled via opts_toolbar(saveaspng = TRUE)) allowing web readers to export the current view as a high-resolution PNG image. For static manuscript submissions, researchers typically render their original ggplot2 object using ggsave() with PDF or TIFF devices, ensuring complete visual parity between the print publication and the interactive online companion figure.

How do you capture clicked elements from ggiraph in a Shiny application?

To capture clicked elements on a ggiraph plot in Shiny, ensure the geometry layer maps a unique identifier to the data_id aesthetic (for example, mapping data_id = sample_id inside geom_point_interactive). In the server function, access the reactive character vector input$[outputId]_selected, where [outputId] matches the name passed to girafeOutput() in the UI. When a user clicks an element, its data_id string is added to this vector. You can configure whether users select a single element or multiple elements simultaneously by passing opts_selection(type = "single") or opts_selection(type = "multiple") to girafe().

What causes tooltips in ggiraph to disappear behind Shiny modal dialogs?

Tooltips disappear behind modal dialogs, drawer panels, or floating cards because of CSS stacking context conflicts. Shiny modal backdrops and containers typically assign a high CSS z-index property (frequently 1050 or above). If the tooltip div generated by ggiraph has a default or lower z-index, the browser places the tooltip beneath the modal container. To resolve this, specify an elevated stacking level in your widget configuration using opts_tooltip(zindex = 9999), ensuring the popup appears above all UI dialogue layers.

Does ggiraph support custom fonts and complex mathematical expressions?

Yes. Because ggiraph utilizes the systemfonts and gdtools packages to calculate accurate font metrics and text boundaries during SVG rendering, it supports custom system typography and Google Fonts loaded into your R session. Mathematical annotations generated via expression() or standard ggplot2 plotmath syntax are converted into vector paths and glyphs within the SVG output, retaining their exact placement and appearance across client devices without requiring external MathJax rendering engines.

Linked hover interactions across multiple charts—often called linked brushing or coordinated views—are achieved by assigning identical data_id values to corresponding observations in different plots. When multiple interactive ggplot objects are composed together (for example, using the patchwork or cowplot packages) and rendered within a single girafe() call, hovering over a data point in one subplot automatically highlights all matching elements bearing that same data_id across all adjacent subplots.

Sources

  • CRAN Package ggiraph Repository — https://cran.r-project.org/package=ggiraph — checked 2026-11-15
  • Official ggiraph Documentation and Vignettes (David Gohel) — https://davidgohel.github.io/ggiraph/ — checked 2026-11-15
  • CRAN Reference Manual: ggiraph (Package Version 0.9.6) — https://cran.r-project.org/web/packages/ggiraph/ggiraph.pdf — checked 2026-11-15
  • GitHub Repository: davidgohel/ggiraph — https://github.com/davidgohel/ggiraph — checked 2026-11-15
  • The ggiraph Book: Interactive Graphics with ggplot2 and ggiraph (ArData) — https://www.ardata.fr/ggiraph-book/ — checked 2026-11-15

Data: Comparison of Interactive R Graphics Packages for Research Workflows

Technical specification, graphics engine, license, ggplot2 compatibility, and Shiny reactivity parameters across major R interactive visualization libraries, compiled from CRAN repository metadata and official documentation.

Period covered: 2026. Coverage: Global.

Comparison of Interactive R Graphics Packages for Research Workflows
PackageLicenseGraphics Engineggplot2 FidelityShiny Event MechanismStandalone HTML Support
ggiraphGPL-3Interactive SVG (dsvg device)High (direct grob preservation)input$_selected character vectorSupported (htmlwidgets)
plotlyMITWebGL and SVG (Plotly.js)Moderate (schema translation via ggplotly)event_data() event listenerSupported (htmlwidgets)
echarts4rApache-2.0HTML5 Canvas and SVG (Apache ECharts)None (requires dedicated syntax)Shiny input bindings via e_dispatch_actionSupported (htmlwidgets)
highcharterMIT package (Highcharts commercial)SVG and HTML5 Canvas (Highcharts)None (requires dedicated syntax)input$_click custom eventsSupported (htmlwidgets)
rbokehMITHTML5 Canvas (BokehJS)None (requires dedicated syntax)rbokeh custom shiny listenersSupported (htmlwidgets)

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about ggiraph: Interactive ggplot2 Graphics in R

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →