How to Create Icon in R



How to Create Icon in R

 

Create Icon in R

This article describes how to create icon in R with transparent background from a ggplot.

Contents:

Prerequisites

Load ggplot2 and create a helper theme for ggplot icon:

library(ggplot2)

# Helper theme for ggplot icon
theme_icon <- function () {
    theme_void() + 
    theme(
      panel.background = element_rect(fill = "transparent", colour = NA), 
      plot.background = element_rect(fill = "transparent", colour = NA), 
      legend.background = element_rect(fill = "transparent", colour = NA), 
      legend.box.background = element_rect(fill = "transparent", colour = NA)
    )
}

Create an icon

  • Create an icon form a ggplot graphic
p <- ggplot(iris, aes(Species, Sepal.Length)) + 
  geom_boxplot(color = "#478bca", fill = "transparent") +
  theme_icon()
  • Save the icon into a 72x72 pixel png or svg format:
# SVG
ggsave(
  filename = "figures/boxplot-icon_72px.svg", p, 
  dpi=72, width = 1, height = 1
  )

# PNG
ggsave(
  filename = "figures/boxplot-icon_72px.png", p, 
  dpi=72, width = 1, height = 1, bg = "transparent"
  )

Create an icon with hexagon sticker

We’ll use the hexSticker R package. imageMagick is required for installing hexSticker. If you have not installed it, please try the following approaches.

library(hexSticker)
p <- ggplot(iris, aes(Species, Sepal.Length)) + 
  geom_boxplot(color = "white", fill = "transparent") +
  theme_icon()
p.sticker <- sticker(
  p, package=" ", p_size=3, 
  s_x=1, s_y=1.1, s_width=1.3, s_height=1.5,
  h_color = "#478bca", h_fill = "#478bca",
  filename="figures/boxplot-icon-sticker.png"
  )
p.sticker



Version: Français





No Comments

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments