Package {ggimage}


Title: Use Image in 'ggplot2'
Version: 0.3.6
Description: Supports image files and graphic objects to be visualized in 'ggplot2' graphic system.
Depends: R (≥ 4.1.0), ggplot2
Imports: digest, ggfun, ggiraph, ggplotify, grid, jsonlite, magick, methods, purrr, rlang, scales, tibble, tools, utils, withr, yulab.utils (≥ 0.1.3)
Suggests: ape, ggtree, gridGraphics, httr, rsvg, testthat (≥ 3.0.0)
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.0
NeedsCompilation: no
Packaged: 2026-09-27 09:30:27 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-09-27 10:20:02 UTC

ggimage: Use Image in 'ggplot2'

Description

Supports image files and graphic objects to be visualized in 'ggplot2' graphic system.

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


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

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)

Arguments

image

image file

Value

ggplot

Author(s)

Guangchuang Yu


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

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

Author(s)

Guangchuang Yu

Examples

library("ggplot2")
library("ggimage")
d <- data.frame(x = c(0.5, 0.52, 0.51),
                y = c(0.5, 0.51, 0.49),
                image = system.file("extdata/Rlogo.png", package = "ggimage"))
## overlapping images are pushed apart
ggplot(d, aes(x, y, image = image)) +
    geom_image_repel(width = 0.1, box.padding = 0.01)
## max.iter = 0 keeps the original coordinates
ggplot(d, aes(x, y, image = image)) +
    geom_image_repel(width = 0.1, max.iter = 0)
## only move them apart horizontally
ggplot(d, aes(x, y, image = image)) +
    geom_image_repel(width = 0.1, 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

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

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