Package {ggimage}


Title: Use Images in 'ggplot2'
Version: 0.3.7
Description: Supports image files and graphic objects to be visualized in 'ggplot2' graphic system. Images can be drawn at data points, used as the background of a plot, or embedded as a sub-plot, and can be read from local files or downloaded from remote services such as 'Pokemon', 'PhyloPic', and emoji and icon collections. An interactive geom is provided for 'HTML' output.
Depends: R (≥ 4.1.0), ggplot2
Imports: digest, ggfun, ggiraph, ggplotify, grid, jsonlite, magick, methods, purrr, rlang, scales, stats, tibble, tools, utils, withr, yulab.utils (≥ 0.1.3)
Suggests: httr, quarto, rsvg, testthat (≥ 3.2.1)
VignetteBuilder: quarto
ByteCompile: true
License: Artistic-2.0
URL: https://github.com/YuLab-SMU/ggimage
BugReports: https://github.com/YuLab-SMU/ggimage/issues
Encoding: UTF-8
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-10-14 11:40:48 UTC; wang
Author: Guangchuang Yu ORCID iD [aut, cre, cph], Shuangbin Xu ORCID iD [ctb], Yonghe Xia [ctb]
Maintainer: Guangchuang Yu <guangchuangyu@gmail.com>
Repository: CRAN
Date/Publication: 2026-10-14 13:12:09 UTC

ggimage: Use Images in 'ggplot2'

Description

Supports image files and graphic objects to be visualized in 'ggplot2' graphic system. Images can be drawn at data points, used as the background of a plot, or embedded as a sub-plot, and can be read from local files or downloaded from remote services such as 'Pokemon', 'PhyloPic', and emoji and icon collections. An interactive geom is provided for 'HTML' output.

Author(s)

Maintainer: Guangchuang Yu guangchuangyu@gmail.com (ORCID) [copyright holder]

Authors:

Other contributors:

See Also

Useful links:


ggproto classes for ggiraph

Description

ggproto classes for ggiraph


autocomplete_name

Description

obtaion suggestions for full names based on partial text name

Usage

autocomplete_name(name, ...)

Arguments

name

partial text name

...

additional parameters

Value

scientific name


Clear the image caches and their diagnostics.

Description

Clear the image caches and their diagnostics.

Usage

clear_image_cache()

Value

NULL, invisibly.

See Also

get_image_cache_stats() reset_image_cache_stats()


download_phylopic

Description

download phylopic images

Usage

download_phylopic(
  id,
  destdir = ".",
  ...,
  reuse = TRUE,
  lock_timeout = getOption("ggimage.phylopic_lock_timeout", 30),
  lock_poll = getOption("ggimage.phylopic_lock_poll", 0.05)
)

Arguments

id

phylopic id

destdir

directory where the downloaded images are to be saved.

...

additional parameters passed to download.file

reuse

whether to reuse existing non-empty regular files

lock_timeout

maximum seconds to wait for a concurrent download lock

lock_poll

seconds between lock acquisition attempts

Details

This function allows users to download phylopic images using phylopic id

Value

a character string (or vector) with downloaded file path

Author(s)

Guangchuang Yu


key drawing function

Description

draw_key_image() draws the legend key of image layers (i.e. geom_image()). The type of the key is determined by the global option ggimage.keytype, which supports "point" (the default when the option is unset), "rect", "image" and "blank" (no key, the behaviour of image layers before the key was implemented). An unsupported value falls back to "point" with a warning.

Usage

draw_key_image(data, params, size)

Arguments

data

A single row data frame containing the scaled aesthetics to display in this key

params

A list of additional parameters supplied to the geom.

size

Width and height of key in mm

Details

The "image" key shows the image carried by the key data, which is the layer's image argument or the images a guide is given with override.aes; ggplot2 has no scale with which to look a per-row image up, so a layer that maps image to a column puts the same image in every key. Without any image to show, the key falls back to the logo bundled with the package.

Image layers have no default colour, so colour can be missing (i.e. NULL) or NA in data, for instance when only alpha is mapped. Such keys fall back to "black", so that alpha stays visible in the legend.

Value

A grid grob


geom_bgimage

Description

add image as background to plot panel.

Usage

geom_bgimage(image, pixel = NULL, x = 0, y = 0, scale = NULL)

Arguments

image

image file, or a magick image object

pixel

the pixel of image to anchor, given as c(col, row) counted from the top-left corner of the image, i.e. col pixels from the left and row pixels from the top. The centre of that pixel is placed on the data point ⁠(x, y)⁠. If NULL (the default) the image is stretched to fill the plot panel and the remaining parameters are ignored.

x

x coordinate of the data point that pixel is anchored to. Only used when pixel is given.

y

y coordinate of the data point that pixel is anchored to. Only used when pixel is given.

scale

number of data units per image pixel. Required when pixel is given; it controls the size of the image in data coordinates. To make the image w data units wide, use scale = w / image_info(image)$width. The extent is given in data units on both axes, so the image keeps its proportions only under coord_fixed(), and is otherwise stretched by the panel's physical shape.

Value

An object that + adds to a plot as a background layer. The background never takes part in the scale ranges: with pixel = NULL it covers the panel whatever the data, and with pixel given the axes can be discrete as well as continuous.

Author(s)

Guangchuang Yu

Examples

library("ggplot2")
library("ggimage")

img <- system.file("extdata/Rlogo.png", package = "ggimage")
d <- data.frame(x = c(1, 2, 3), y = c(1, 2, 1.5))
p <- ggplot(d, aes(x, y)) +
    scale_x_continuous(limits = c(0, 4)) +
    scale_y_continuous(limits = c(0, 4))

## by default the image is stretched to fill the panel
p + geom_bgimage(img) + geom_point()

## with `pixel`, the image is placed in data coordinates instead: the
## centre of the bottom-left pixel is anchored to the origin, and `scale`
## sets the size
info <- magick::image_info(magick::image_read(img))
p + geom_bgimage(img, pixel = c(1, info$height), x = 0, y = 0,
                 scale = 4 / info$width) + geom_point()

geom_emoji

Description

geom layer for using emoji image

Usage

geom_emoji(
  mapping = NULL,
  data = NULL,
  inherit.aes = TRUE,
  na.rm = FALSE,
  by = "width",
  ...
)

Arguments

mapping

aes mapping

data

data

inherit.aes

whether inherit aes mapping from ggplot()

na.rm

whether remove NA values

by

one of 'width' or 'height' for specifying size

...

additional parameter

Value

ggplot2 layer

Author(s)

Guangchuang Yu


geom_flag

Description

geom layer for using flag image

Usage

geom_flag(
  mapping = NULL,
  data = NULL,
  inherit.aes = TRUE,
  na.rm = FALSE,
  by = "width",
  ...
)

Arguments

mapping

aes mapping

data

data

inherit.aes

whether inherit aes mapping from ggplot()

na.rm

whether remove NA values

by

one of 'width' or 'height' for specifying size

...

additional parameter

Value

ggplot2 layer

Author(s)

Guangchuang Yu


geom_icon

Description

geom layer for using icon

Usage

geom_icon(
  mapping = NULL,
  data = NULL,
  inherit.aes = TRUE,
  na.rm = FALSE,
  by = "width",
  ...
)

Arguments

mapping

aes mapping

data

data

inherit.aes

whether inherit aes mapping from ggplot()

na.rm

whether remove NA values

by

one of 'width' or 'height' for specifying size

...

additional parameter

Value

ggplot2 layer

Author(s)

Guangchuang Yu


geom_image

Description

geom layer for visualizing image files

Usage

geom_image(
  mapping = NULL,
  data = NULL,
  stat = "identity",
  position = "identity",
  inherit.aes = TRUE,
  na.rm = FALSE,
  by = "width",
  nudge_x = 0,
  nudge_y = 0,
  use_cache = TRUE,
  width = NULL,
  height = NULL,
  ...
)

Arguments

mapping

aes mapping

data

data

stat

stat

position

position

inherit.aes

logical, whether inherit aes from ggplot()

na.rm

logical, whether remove NA values

by

one of 'width' or 'height'

nudge_x

horizontal adjustment to nudge image

nudge_y

vertical adjustment to nudge image

use_cache

logical, whether to use image caching for better performance (default: TRUE)

width, height

Image width and height in native panel units, matching the plotting units used by the size/by behavior. They can be mapped per row via aes(width = ..., height = ...) or set for the whole layer. They override size (and therefore also size = Inf and by):

  • only width is provided, the height is derived from the image ratio;

  • only height is provided, the width is derived from the image ratio;

  • both are provided, the image is drawn in exactly that box, which may distort it when the ratio of the box differs from the image ratio.

coord_fixed() controls the physical aspect of the panel; it does not reinterpret these values. Values that are NA, not finite or not positive are ignored, and the size/by behavior is used for the affected image.

...

additional parameters

Value

geom layer

Aesthetics

geom_image() understands the following aesthetics (required aesthetics are in bold):

colour and alpha are applied per row: colour tints the image and alpha sets its opacity, so both aes(colour = ...) and aes(alpha = ...) work. alpha is an ordinary ggplot2 aesthetic, so its default continuous scale maps the data range onto ⁠[0.1, 1]⁠; add scale_alpha_identity() to pass the values through unchanged.

image may also be given as a list-column of magick images, one image per row, in addition to a path or a URL per row. Such images are cached by their content rather than by object identity.

Author(s)

Guangchuang Yu

Examples

## Not run: 
library("ggplot2")
library("ggimage")
set.seed(2017-02-21)
d <- data.frame(x = rnorm(10),
                y = rnorm(10),
                image = sample(c("https://www.r-project.org/logo/Rlogo.png",
                                "https://jeroenooms.github.io/images/frink.png"),
                              size=10, replace = TRUE)
               )
# With caching enabled (default)
ggplot(d, aes(x, y)) + geom_image(aes(image=image))

# With caching disabled
ggplot(d, aes(x, y)) + geom_image(aes(image=image), use_cache=FALSE)

# Per-row image size, via the `width` and `height` aesthetics
ggplot(d, aes(x, y)) +
    geom_image(aes(image=image, width=abs(x)/10, height=abs(y)/10))

# Only one of them: the other dimension keeps the ratio of the image
ggplot(d, aes(x, y)) + geom_image(aes(image=image, width=abs(x)/10))

## End(Not run)

Create interactive image of ggimage

Description

The geometry is based on geom_image(). See the documentation for those functions for more details.

Usage

geom_image_interactive(...)

Arguments

...

see also the parameters of geom_image() of ggimage

Examples

## Not run: 
library("ggplot2")
library("ggimage")
library("ggiraph")
set.seed(2017-02-21)
d <- data.frame(x = rnorm(10),
                y = rnorm(10),
                image = sample(c("https://www.r-project.org/logo/Rlogo.png",
                                "https://jeroenooms.github.io/images/frink.png"),
                              size=10, replace = TRUE)
               )
d$id <- sample(10)
p <- ggplot(d, aes(x, y)) + 
     geom_image_interactive(aes(image=image, tooltip = id, data_id = id))
girafe(ggobj = p)

## End(Not run)

geom_image_repel

Description

geom layer for visualizing image files with basic overlap avoidance

Usage

geom_image_repel(
  mapping = NULL,
  data = NULL,
  stat = "identity",
  position = "identity",
  inherit.aes = TRUE,
  na.rm = FALSE,
  by = "width",
  nudge_x = 0,
  nudge_y = 0,
  use_cache = TRUE,
  width = NULL,
  height = NULL,
  max.iter = 100,
  force = 0.1,
  box.padding = 0,
  direction = "both",
  ...
)

Arguments

mapping

aes mapping

data

data

stat

stat

position

position

inherit.aes

logical, whether inherit aes from ggplot()

na.rm

logical, whether remove NA values

by

one of 'width' or 'height'

nudge_x

horizontal adjustment to nudge image

nudge_y

vertical adjustment to nudge image

use_cache

logical, whether to use image caching for better performance

width, height

Image width and height in native panel units, see geom_image(). Only one of them keeps the aspect ratio of the image.

max.iter

non-negative whole number of displacement iterations. max.iter = 0 keeps the original coordinates (and force = 0 does the same).

force

non-negative number, the fraction of the current overlap that is resolved in one iteration (each image of an overlapping pair moves by force * overlap / 2). Larger values converge faster but produce bigger jumps.

box.padding

non-negative number, extra space added around every image box, in the same units as width/height. Repelled images are kept at least box.padding apart.

direction

one of 'both', 'x' or 'y', the axis (or axes) along which images are allowed to move. Overlap is always detected on both axes; direction only restricts the displacement, so direction = "x" slides overlapping images horizontally until they no longer overlap.

...

additional parameters

Details

geom_image_repel() draws images like geom_image(), but moves images that overlap each other apart before drawing them. The displacement is computed offline (no network, no rendering, no ggrepel dependency) from the bounding boxes of the images, so the result is deterministic: the same plot always produces the same layout.

The algorithm works on the centres of the images, after they have been nudged (nudge_x/nudge_y) and transformed by the coordinate system (this is the space in which width/height are expressed, i.e. fractions of the panel):

  1. each image gets an axis aligned box of size width + box.padding by height + box.padding;

  2. for every pair of boxes that overlap on both axes, the two images are pushed apart along the allowed direction, by force * overlap / 2 each, away from each other;

  3. step 2 is repeated at most max.iter times, stopping early once no pair overlaps. The residual overlap after max.iter iterations is about (1 - force)^max.iter of the initial one, so the default (force = 0.1, max.iter = 100) leaves essentially no overlap.

which keeps the result reproducible. For large inputs, an adaptive uniform-grid broad phase estimates candidate density before each sweep: sparse layouts use one immutable grid, while dense layouts use the full scan when grid lookup and candidate handling would cost more than checking every pair. If a sparse-grid sweep moves any image, its candidate set is no longer current; the remainder of that sweep conservatively falls back to the full scan. The grid costs O(n + k) per sweep for k candidate checks (with O(n^2) worst-case dense behaviour), while small inputs retain the full pair scan. The cleanup is hard-capped at 256 sweeps so dense inputs cannot make cleanup grow with n beyond that fixed number of sweeps.

Images are pushed away from each other only, they are not kept inside the panel, and images are never re-ordered or removed. Images with size = Inf (e.g. the background image added by geom_bgimage()) and images that cannot be loaded are ignored by the repulsion: they keep their original position and do not push the other images around.

The width of an image that is sized through size/by (instead of an explicit width) is derived by grid from its height and from the physical aspect of the panel. geom_image_repel() uses the aspect reported by the coordinate system (coord_fixed(), exact) and assumes a square panel otherwise, which over-estimates the width of a panel that is wider than it is high. Pass explicit width/height when the exact box matters.

Value

geom layer

Aesthetics

geom_image_repel() understands the same aesthetics as geom_image() (required aesthetics are in bold):

colour and alpha are applied to the drawn image and do not influence the repulsion, which is computed from x, y, size, width and height alone.

Author(s)

Guangchuang Yu

Examples

library("ggplot2")
library("ggimage")
d <- data.frame(x = c(0.50, 0.52, 0.51),
                y = c(0.50, 0.51, 0.49),
                image = system.file("extdata/Rlogo.png", package = "ggimage"))
## the fixed scale matters: with the default limits the three points would
## be spread over the whole panel and would not overlap at all
p <- ggplot(d, aes(x, y, image = image)) +
    scale_x_continuous(limits = c(0, 1)) +
    scale_y_continuous(limits = c(0, 1))
## as they are, the images overlap
p + geom_image(width = 0.12)
## ... and are pushed apart by geom_image_repel()
p + geom_image_repel(width = 0.12, box.padding = 0.01)
## max.iter = 0 keeps the original coordinates
p + geom_image_repel(width = 0.12, max.iter = 0)
## only move them apart horizontally
p + geom_image_repel(width = 0.12, direction = "x")

geom_phylopic

Description

geom layer for using phylopic image

Usage

geom_phylopic(
  mapping = NULL,
  data = NULL,
  inherit.aes = TRUE,
  na.rm = FALSE,
  by = "width",
  image_fun = function(x) magick::image_background(x, color = "none", flatten = FALSE),
  ...
)

Arguments

mapping

aes mapping

data

data

inherit.aes

whether inherit aes mapping from ggplot()

na.rm

whether remove NA values

by

one of 'width' or 'height' for specifying size

image_fun

a function to process magick-image objects, default is function(x)magick::image_background(x, color = "none", flatten = FALSE).

...

additional parameter

Value

ggplot2 layer

Author(s)

Guangchuang Yu


Create interactive phylopic of ggimage

Description

The geometry is based on geom_phylopic(). See the documentation for those functions for more details.

Usage

geom_phylopic_interactive(...)

Arguments

...

see also the parameters of geom_phylopic() of ggimage


geom_pokemon

Description

geom layer for using pokemon image

Usage

geom_pokemon(
  mapping = NULL,
  data = NULL,
  inherit.aes = TRUE,
  na.rm = FALSE,
  by = "width",
  ...
)

Arguments

mapping

aes mapping

data

data

inherit.aes

whether inherit aes mapping from ggplot()

na.rm

whether remove NA values

by

one of 'width' or 'height' for specifying size

...

additional parameter

Value

ggplot2 layer

Author(s)

Guangchuang Yu


geom_subview

Description

subview geom

Usage

geom_subview(
  mapping = NULL,
  data = NULL,
  width = 0.1,
  height = 0.1,
  x = NULL,
  y = NULL,
  subview = NULL
)

Arguments

mapping

aes mapping, requires 'x', 'y' and 'subview'

data

data frame

width

width

height

height

x

x position of subview. This parameter works if mapping and data is not provided

y

y position of subview. This parameter works if mapping and data is not provided

subview

subview to plot, if not provided in data and specify by mapping

Details

Subviews can be placed in three ways. The positions and the subviews may be taken from the plot's own mapping, the usual 'ggplot2' idiom:

ggplot(df, aes(x, y, subview = pie)) + geom_subview()
ggplot(df, aes(x, y)) + geom_subview(aes(subview = pie))

They may also all be given to the layer, with the positions and the subviews taken from its own data:

geom_subview(aes(x = x, y = y, subview = pie, width = width, height = width),
             data = df)

For one or more subviews given by position, the first argument is read as the subview rather than as a mapping:

geom_subview(legend, x = 10, y = 50)
geom_subview(df$pie, df$x, df$y, width = df$width, height = df$height)

A geom_subview() whose aesthetics are not all supplied by its own arguments is resolved when it is added to a plot, so that an x, y or subview inherited from ggplot() can be seen; what is missing from both places is reported then, at the +, with the same message.

Value

layer

Author(s)

guangchuang yu


geom_worldcup2018

Description

geom layer for wordcup 2018

Usage

geom_worldcup2018(
  mapping = NULL,
  data = NULL,
  inherit.aes = TRUE,
  na.rm = FALSE,
  by = "width",
  ...
)

Arguments

mapping

aes mapping

data

data

inherit.aes

whether inherit aes mapping from ggplot()

na.rm

whether remove NA values

by

one of 'width' or 'height' for specifying size

...

additional parameter

Value

ggplot2 layer

Author(s)

Guangchuang Yu


Get or set the global image cache policy.

Description

Cache limits may also be supplied with options(): use ggimage.image_cache_capacity, ggimage.image_cache_ttl, ggimage.image_cache_bytes, and ggimage.image_cache_eviction for both caches, or the corresponding ⁠ggimage.image_cache_base_*⁠ and ⁠ggimage.image_cache_transform_*⁠ options independently. Byte limits are approximate object-size guardrails rather than process-memory measurements. The default capacity, TTL, and byte cap are infinite, preserving the historical unbounded cache. eviction is one of "lru", "fifo", or "none"; the last value disables capacity and byte eviction. clock is intended for deterministic tests and should return seconds or POSIXct.

Usage

get_image_cache_policy()

set_image_cache_policy(
  capacity = NULL,
  ttl = NULL,
  eviction = NULL,
  base_capacity = NULL,
  transform_capacity = NULL,
  base_ttl = NULL,
  transform_ttl = NULL,
  bytes = NULL,
  base_bytes = NULL,
  transform_bytes = NULL,
  clock = NULL
)

Arguments

capacity, ttl

Optional shared capacity (number of entries) and TTL (seconds). NULL leaves the current option unchanged.

eviction

Optional eviction policy: "lru", "fifo", or "none".

base_capacity, transform_capacity

Cache-specific capacities.

base_ttl, transform_ttl

Cache-specific TTLs in seconds.

bytes

Optional shared estimated byte cap for each cache. NULL leaves the current option unchanged. This is an estimate, not a process-memory measurement; native image buffers may be larger than the estimate.

base_bytes, transform_bytes

Cache-specific estimated byte caps.

clock

Optional function used as the cache clock.

Value

get_image_cache_policy() returns a policy list. The setter returns the previous policy invisibly.


Return image cache hit, miss, eviction, expiry, and size diagnostics.

Description

The bytes and entries values are estimates/current counts. Byte estimates use object.size() (and a pixel-based lower bound for magick images), so native ImageMagick allocations are not accounted for exactly.

Usage

get_image_cache_stats()

get_image_cache_diagnostics()

Value

A list with base and transform named diagnostic vectors.


ggbackground

Description

set background for ggplot

Usage

ggbackground(gg, background, ...)

Arguments

gg

gg object

background

background image

...

additional parameter to manipulate background image, see also geom_image

Value

gg object, with the background as its first layer. The layer sits on one of the observations the plot already has, so it does not widen the axis ranges and needs no continuous axis. The observation is taken from the plot-level aes(), or from the first layer that maps x and y.

Author(s)

guangchuang yu


ggpreview

Description

preview a plot befor saving it to a file.

Usage

ggpreview(
  filename = NULL,
  plot = last_plot(),
  width = NA,
  height = NA,
  units = "in",
  ...
)

Arguments

filename

If it is not NULL, the previewed figure will be save to the file

plot

any plot that supported by the 'ggplotify' package

width

width of the figure

height

height of the figure

units

units of the 'width' and 'height'

...

additional parameters pass to ggsave() if filename is not NULL

Value

a preview of the figure

Author(s)

Guangchuang Yu


image_read2

Description

read image (by magick::image_read) with the ability to remove marginal empty space

Usage

image_read2(path, ..., cut_empty_space = TRUE)

Arguments

path

file path

...

additional parameters that pass to magick::image_read

cut_empty_space

whether remove marginal empty space

Value

magick-image object

Author(s)

Guangchuang Yu


list.flag

Description

list available flag

Usage

list.flag()

Value

flag vector

Author(s)

Guangchuang Yu


list.icon

Description

list available icon

Usage

list.icon()

Value

icon vector

Author(s)

Guangchuang Yu


list.pokemon

Description

list available pokemon

Usage

list.pokemon()

Value

pokemon vector

Author(s)

Guangchuang Yu


list.worldcup2018

Description

list flags of worldcup 2018

Usage

list.worldcup2018()

Value

flag vector

Author(s)

Guangchuang Yu


phylopic_uid

Description

query phylopic to get uid from scientific name

Usage

phylopic_uid(name, seed = 123)

Arguments

name

scientific name

seed

The random seed to use to generate the same uid, because a name might have many uid, the function will extract one of them randomly, default is 123.

Value

phylopic uid

Author(s)

Guangchuang Yu


Objects exported from other packages

Description

These objects are imported from other packages. Follow the links below to see their documentation.

ggplotify

as.ggplot(), as.grob()


Reset image cache hit/miss and eviction/expiry counters.

Description

Cache entries are retained; use clear_image_cache() to clear entries and reset these counters together.

Usage

reset_image_cache_stats()

theme_nothing

Description

A theme that only show the plot panel

Usage

theme_nothing(base_size = 11, base_family = "")

Arguments

base_size

font size

base_family

font family

Value

ggplot2 theme

Author(s)

Guangchuang Yu


theme_transparent

Description

transparent background theme

Usage

theme_transparent(...)

Arguments

...

additional parameter to tweak the theme

Value

ggplot object

Author(s)

Guangchuang Yu with contributions from Hugo Gruson