Giter Site home page Giter Site logo

ggimage's Introduction

ggimage: Use Image in ‘ggplot2’

CRAN_Status_Badge gitter DOI

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

✍️ Authors

Guangchuang YU https://guangchuangyu.github.io

School of Basic Medical Sciences, Southern Medical University

saythanks

⏬ Installation

Get the released version from CRAN:

## include BioC repo for dependencies
setRepositories(ind=1:2)
install.packages("ggimage")

Or the development version from github:

setRepositories(ind=1:2)
## install.packages("devtools")
devtools::install_github("GuangchuangYu/ggimage")

📖 Vignette

For more details, please refer to the online vignette.

ggimage's People

Contributors

amazongodman avatar brendan-r avatar guangchuangyu avatar xiangpin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ggimage's Issues

Make a ggplot 0,0 XY coordinate to coincide with a specific point of a background image

I have recently came across your package, I am a little excited and skeptical at the same time. I am developing a new package in R and need to solve one important issue. Maybe your knowledge can help me and maybe cooperate in the future. I am going to explain my issue:

I would like to combine two relevant things:

  • A ggplot plot.
  • And a background image.

However, I would like to do so by taking into consideration a particular point of the background image. I would like a specific point in the background image to be the XY coordinate (0,0) of the ggplot.

Data

Let's start with some data to illustrate what I want. Let's load iris dataset.

data(iris)

We create the ggplot()

Now, let's create this scatterplot with the petal measurements.

g <- ggplot(iris, aes(x= Petal.Length, y = Petal.Width)) + 
  geom_point() +
  xlim(0,7) + ylim(0,2.5) +
  theme_minimal()
print(g)

enter image description here

Background image

This is the background image I would like to implement.

enter image description here

Selecting the XY (0,0) coordinate in the image

This is the point of the background image where I would like to anchor the XY (0,0) of the ggplot.

enter image description here

Expected output

The expected output must be anchoring the XY 0,0 of the ggplot to the selected point of the background image, no matter the size of the image.

It would be something like this:

enter image description here

How can I do it?

Error in geom_subview

I meet an error when I try to plot a bubble plot following the tutorial (https://guangchuangyu.github.io/cn/2017/07/pie-version-of-bubble-plot/).

when I use the following code, an error occurred.
p <- ggplot(crime, aes(murder, Robbery)) + geom_subview(leg1, x=10, y=50) + geom_subview(crime$pie, crime$murder, crime$Robbery, width=crime$width, height=crime$height) + geom_text_repel(aes(label=state))

Error in geom_subview(leg1, x = 10, y = 50) :
x aesthetic mapping should be provided

Could you please help me to solve it.

Weird error when try to color too much images

Hello,

I tried to plot 300 images with geom_image. It worked, but when I try to color images, most of images vanished.

Do you know why ?

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

# create a df

set.seed(2017-02-21)
d <- data.frame(x = rnorm(300),
                y = rnorm(300),
                image = sample(c("https://www.r-project.org/logo/Rlogo.png",
                                 "https://jeroenooms.github.io/images/frink.png"),
                               size=10, replace = TRUE)
)
# plot2
ggplot(d, aes(x, y)) + geom_image(aes(image=image)", size=.05)

Rplot

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

# create a df

set.seed(2017-02-21)
d <- data.frame(x = rnorm(300),
                y = rnorm(300),
                image = sample(c("https://www.r-project.org/logo/Rlogo.png",
                                 "https://jeroenooms.github.io/images/frink.png"),
                               size=10, replace = TRUE)
)
# plot2
ggplot(d, aes(x, y)) + geom_image(aes(image=image), color="red", size=.05)

Rplot03

> sessionInfo()
R version 4.0.5 (2021-03-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19041)

Matrix products: default

Random number generation:
 RNG:     Mersenne-Twister 
 Normal:  Inversion 
 Sample:  Rounding 
 
locale:
[1] LC_COLLATE=French_France.1252  LC_CTYPE=French_France.1252    LC_MONETARY=French_France.1252
[4] LC_NUMERIC=C                   LC_TIME=French_France.1252    

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggimage_0.2.8       ggplot2_3.3.3       oligoClasses_1.52.0

loaded via a namespace (and not attached):
 [1] SummarizedExperiment_1.20.0 tidyselect_1.1.1            purrr_0.3.4                 lattice_0.20-41            
 [5] colorspace_2.0-0            vctrs_0.3.8                 generics_0.1.0              stats4_4.0.5               
 [9] utf8_1.2.1                  gridGraphics_0.5-1          rlang_0.4.11                pillar_1.6.0               
[13] glue_1.4.2                  withr_2.4.2                 DBI_1.1.1                   BiocGenerics_0.36.1        
[17] affyio_1.60.0               matrixStats_0.58.0          GenomeInfoDbData_1.2.4      rvcheck_0.1.8              
[21] foreach_1.5.1               lifecycle_1.0.0             zlibbioc_1.36.0             MatrixGenerics_1.2.1       
[25] Biostrings_2.58.0           munsell_0.5.0               gtable_0.3.0                codetools_0.2-18           
[29] labeling_0.4.2              Biobase_2.50.0              ff_4.0.4                    IRanges_2.24.1             
[33] GenomeInfoDb_1.26.7         curl_4.3.1                  parallel_4.0.5              fansi_0.4.2                
[37] Rcpp_1.0.6                  scales_1.1.1                BiocManager_1.30.12         DelayedArray_0.16.3        
[41] S4Vectors_0.28.1            magick_2.7.1                jsonlite_1.7.2              XVector_0.30.0             
[45] bit_4.0.4                   digest_0.6.27               dplyr_1.0.5                 GenomicRanges_1.42.0       
[49] cli_2.5.0                   tools_4.0.5                 bitops_1.0-7                magrittr_2.0.1             
[53] RCurl_1.98-1.3              tibble_3.1.1                crayon_1.4.1                pkgconfig_2.0.3            
[57] ellipsis_0.3.2              Matrix_1.3-2                ggplotify_0.0.6             iterators_1.0.13           
[61] R6_2.5.0                    compiler_4.0.5             

list.icon

the ggimage::list.icon function uses a helper function which looks for png files. This is really not useful, as the icons are svg files. Below a suggestion for a modification - happy to submit pull request if interested.

list_images <- function (url, filetype = "svg") 
{
  x <- readLines(url)
  y <- x[grep(paste0("title=\"[a-zA-Z0-9\\-]+\\.", filetype), x)]
  sub(paste0(".*title=\"([a-zA-Z0-9\\-]+)\\.",filetype, ".*"), "\\1", y)
}

list_icon <- function(){
  list_images("https://github.com/ionic-team/ionicons/tree/master/src/svg")
}

head(list_icon(), 10)
#>  [1] "accessibility-outline" "accessibility-sharp"   "accessibility"        
#>  [4] "add-circle-outline"    "add-circle-sharp"      "add-circle"           
#>  [7] "add-outline"           "add-sharp"             "add"                  
#> [10] "airplane-outline"

keeping aspect ratio of images when coords change

When changing ggplot coords (fixed, equal,...) the images get distorted.
How to keep the aspect ratio independent of coord_*?

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)
)
ggplot(d, aes(x, y)) + geom_image(aes(image=image), size=.2)
ggplot(d, aes(x, y)) + geom_image(aes(image=image), size=.2) 
ggplot(d, aes(x, y)) + coord_fixed(2) + geom_image(aes(image=image), size=.2) 
 

image color example not working

Hi
I am having issues reproducing the color examples.
I just installed the dev version of ggimage with devtools.

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)
)

ggplot(d, aes(x, y)) + geom_image(aes(image=image), size=.05, color = "red")

This is the image I get. No red color.

image

Any ideas?

R version 3.4.3 (2017-11-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS  10.14.1

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] dsDesigner_0.1.0 magick_2.0       ggimage_0.2.0    ggplot2_3.1.0   

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.0         git2r_0.23.0       pillar_1.1.0       compiler_3.4.3     plyr_1.8.4        
 [6] bindr_0.1.1        tools_3.4.3        digest_0.6.18      memoise_1.1.0      jsonlite_1.6      
[11] tibble_1.4.2       gtable_0.2.0       pkgconfig_2.0.2    rlang_0.3.0.9001   ggplotify_0.0.3   
[16] cli_1.0.0          rstudioapi_0.8     rvcheck_0.1.3      curl_3.2           yaml_2.2.0        
[21] bindrcpp_0.2.2     knitr_1.20         httr_1.3.1         withr_2.1.2.9000   dplyr_0.7.8       
[26] gridGraphics_0.3-0 devtools_1.13.5    grid_3.4.3         tidyselect_0.2.5   glue_1.3.0        
[31] R6_2.3.0           purrr_0.2.5        magrittr_1.5       scales_1.0.0.9000  assertthat_0.2.0  
[36] colorspace_1.3-2   labeling_0.3       utf8_1.1.3         lazyeval_0.2.1     munsell_0.5.0     
[41] crayon_1.3.4   

phylopic_uid & phylopic_uid_item return "subscript out of bounds" errors when a species is not found

When using phylopic_uid, sometimes it will fail with error Error in jsonlite::fromJSON(url)$result[[1]] : subscript out of bounds whenever Phylopic doesn't have the species in their database. For a small set of species names, troubleshooting this isn't too hard, but for longer species lists, figuring out which species are causing the problem can add up to a significant timesink.

Specifically, the problem lies in the ggimage internal function phylopic_uid_item, and its assumption that you will always get at least one item from jsonlite::fromJSON(url)$result. It would be safer to first save the object to a variable, and then check for the length before proceeding.

My proposed fix would be to add an if-else statement checking the length of the results item as follows:

phylopic_uid_item <- function (name) 
{
    x <- gsub("[^a-zA-Z]+", "+", name)
    url <- paste0("http://phylopic.org/api/a/name/search?text=", 
                  x, "&options=scientific+json")
    results <- jsonlite::fromJSON(url)$result   
    if (length(results)==0){
        return(NA)
    } else{
    res <- results[[1]]
    for (id in res$uid) {
        uid <- phylopic_valid_id(id)
        if (!is.na(uid)) 
            break
    }
    return(uid)}
}

As a minimal test case, you can compare the output of phylopic_uid("Procavia_capensis") (which always works) with phylopic_uid("Chlorocebus_sabaeus") (which fails currently, but returns NA with my solution.

If this works well for you, then I can also submit a pull request with the change.

Edit:
Additionally, this fix would require changing "vapply" to "sapply" in phylopic_uid to allow NA values.

geom_image(): flip and rotate an image

Is it possible to rotate/flip/fop an image with geom_image()?

I would like to get the mirror-image based on a binary variable. For example, given that z is either "A" or "B" have points which are "B" be the mirror-image.

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

set.seed(2017-02-21)
d <- data.frame(x = rnorm(10),
                y = rnorm(10),
                z = sample(c("A","B")),
                image = sample(c("https://www.r-project.org/logo/Rlogo.png", "https://jeroenooms.github.io/images/frink.png"), size=10, replace = TRUE))

Incorrect location of the images

I have the following code for three bacteria with three colors. It doesn't seem that the images are correctly placed.

library(ggplot2)
library(ggimage)

pos = position_jitterdodge(jitter.width = 0, jitter.height = 0.5, seed=1)

set.seed(1)
dat <- data.frame(y=1, x=sample(c('A','B','C'), 60, replace = T) , cat=sample(c(1, 2, 3),60, replace = T))

img <- data.frame(cat=c(1,2,3), 
                  img=c('http://pngimg.com/uploads/bacteria/bacteria_PNG34.png',
                        'https://cdn.pixabay.com/photo/2013/07/13/10/15/bacteria-156870_960_720.png',
                        'http://pngimg.com/uploads/virus/virus_PNG14.png'))

df <- merge(dat, img, by='cat', all=TRUE)

df$cat <- as.factor(df$cat)

library(ggrepel)
ggplot(df, aes(x=x,y=y,color=cat)) + 
    geom_image(aes(image=img), position = pos, alpha=0.4) +
    geom_point(position = pos, size=3, alpha=0.4) 

The image should have the same color and the same position with the points.

> sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggrepel_0.8.0 ggimage_0.1.7 ggplot2_3.0.0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.18       knitr_1.18         bindr_0.1.1        magrittr_1.5       tidyselect_0.2.4  
 [6] munsell_0.5.0      colorspace_1.3-2   R6_2.2.2           rlang_0.2.2        plyr_1.8.4        
[11] dplyr_0.7.6        tools_3.4.2        grid_3.4.2         gtable_0.2.0       ggplotify_0.0.3   
[16] withr_2.1.2        gridGraphics_0.3-0 digest_0.6.16      yaml_2.1.16        lazyeval_0.2.1    
[21] assertthat_0.2.0   tibble_1.4.2       bindrcpp_0.2.2     purrr_0.2.5        curl_3.1          
[26] glue_1.3.0         labeling_0.3       compiler_3.4.2     pillar_1.2.1       rvcheck_0.1.0     
[31] magick_1.6         scales_1.0.0       pkgconfig_2.0.2 

Fixing aspect ratio of images when resizing window/using ggsave

When making a plot with geom_image, the images are distorted when the device window dimensions are changed. More importantly, this also occurs when trying to save to file with ggsave. This makes geom_image unusable for me in almost all use cases.

I've put up a question on StackOverflow that was also answered/solved. It's quite the workaround though, so I was wondering if this could be implemented in the package itself.

.eps files grainy

Is there a way to get .eps images to work well? With image='filename.pdf' the image is very clear, but with image='filename.eps' it's very grainy, as if it has been converted to a lower res raster image.

This is perhaps related to this closed issue on vector images
#2 (comment)

Error in installation of package

When I run:

setRepositories(ind=1:2)
install.packages("ggimage")

I get the following error message:

Error in system("convert --version", intern = TRUE, ignore.stderr = TRUE) :
error in running command
Error : unable to load R code in package ‘gridGraphics’
ERROR: lazy loading failed for package ‘gridGraphics’

  • removing ‘/Library/Frameworks/R.framework/Versions/3.4/Resources/library/gridGraphics’
    Warning in install.packages :
    installation of package ‘gridGraphics’ had non-zero exit status
    ERROR: dependency ‘gridGraphics’ is not available for package ‘base2grob’
  • removing ‘/Library/Frameworks/R.framework/Versions/3.4/Resources/library/base2grob’
    Warning in install.packages :
    installation of package ‘base2grob’ had non-zero exit status
    ERROR: dependencies ‘base2grob’, ‘gridGraphics’ are not available for package ‘ggimage’
  • removing ‘/Library/Frameworks/R.framework/Versions/3.4/Resources/library/ggimage’
    Warning in install.packages :
    installation of package ‘ggimage’ had non-zero exit status

The downloaded source packages are in
‘/private/var/folders/x2/6jl2tndn1dq_dd1_cf6mksgw0000gn/T/Rtmpr4AL8w/downloaded_packages’

Feature Request: full gif support

Hi @GuangchuangYu ,

at first great work. Thanks for this helpful library!

The geom_image function works perfect with svg files, but unfortunately there appears an "error" when a gif image is used.
Only the first image is displayed, even if the package gganimate is used to create gifs with a plot.
I understand that a gif file is based on multiple images, and the first image displayed might be sufficient, but I need the full animation.

Is there a way to add the support of a full gif animation?
If this is possible, I would be very happy about an implementation.

Greetings

# R 4.2.1, Windows 10

x_x <- data.frame("V1"=1:3, "V2"= (1:3)^2, "type"=c("a", "b", "b"))

x_y <- ggplot() +
  geom_point(data=x_x, aes(V1, V2)) +
  ggimage::geom_image(data=x_x, aes(V1, V2, image='Sample.gif'))

x_y

x_z <- x_y +
  gganimate::transition_states(
    type,
    transition_length = 2,
    state_length = 1
  )

x_z

# sample gif:

Sample

Error trying to render SVG from local file

Hi there. Any idea what might be going on here? I have it traced down to an imagemagick issue, but I don't know what ggimage is doing in between?

Ignoring unknown parameters: image_colour, widthError in magick_image_readpath(path, density, depth, strip) : 
  Magick: must specify image size `/var/folders/c2/ytg8vml53vx74sn6t_m6vkpr0000gn/T//RtmpY3MFxc/magick-88792sonmStVmlI72' @ error/mvg.c/ReadMVGImage/186

Error message with geom_flag

Hi there,

I've been trying to add flags to a bar plot using geom_flag. I've been using the following code:

countrytotal$COWcode <- countrycode(countrytotal$Fleet, "country.name", "cown")
countrytotal$countryname <- countrycode(countrytotal$COWcode, "cown", "country.name")
countrytotal$iso2 <- countrycode(countrytotal$countryname, "country.name", "iso2c")
countrytotal$iso2_lower <- tolower(countrytotal$iso2)

plot1 <- ggplot(data=countrytotal, aes(x=Fleet, y=totalcatch)) +
geom_bar(stat="identity") +
coord_flip() + expand_limits(y = -4)
plot1 + geom_flag(aes(y =-4, image = iso2_lower), data=countrytotal)

I continue to get the error message of Error in class(grobs) <- "gList" : attempt to set an attribute on NULL.

Any thoughts on what may be going on? Thank you.

`unite_()` was deprecated in tidyr 1.2.0.

library(ggmosaic)
library(ggplot2)

ggplot(titanic) +
geom_mosaic(aes(x = product(Class), fill = Survived))

For this demonstration example, it returns a warning message:
unite_() was deprecated in tidyr 1.2.0.
Please use unite() instead.

Hope the function will be updated soon to avoid breakdown in the long term.

TODO

  • support setting color and alpha in aes()

image legend key

#!/bin/env Rscript
library(ggimage)
set.seed(2018-12-11)
d  <-  data.frame(x=1:10, y=1:10,
                  type = sample(LETTERS[1:3], 10, replace=T),
                  angle = runif(10, 0, 360))

options(ggimage.keytype = "point")
ggplot(d, aes(x, y, colour=type, angle=angle)) +
    geom_pokemon(aes(image=ifelse(x>5, 'pikachu', 'tauros')))


windows()
options(ggimage.keytype = "rect")
ggplot(d, aes(x, y, colour=type, angle=angle)) +
    geom_pokemon(aes(image=ifelse(x>5, 'pikachu', 'tauros')))

windows()
options(ggimage.keytype = "image")
ggplot(d, aes(x, y, colour=type, angle=angle)) +
    geom_pokemon(aes(image=ifelse(x>5, 'pikachu', 'tauros')), angle=45)

image-key

For legend key of image color, I implemented three optional keytypes:

  1. solid circle dots ❤️
  2. rectangle 👍
  3. image (the R logo, similar to text color legend that use ) 😄

error with geom_flag

I am trying to reproduce the geom_flag example in the link:
https://mran.microsoft.com/snapshot/2018-05-23/web/packages/ggimage/vignettes/ggimage.html

But when I am running this code:

f <- system.file("extdata/medals.txt", package="ggimage")
medals <- read.table(f, header=TRUE)
p <- ggplot(medals, aes(Country, count)) + geom_col(aes(fill = medal), width = .8)

p + geom_flag(y = -2, aes(image = code)) +
coord_flip() + expand_limits(y = -2) +
scale_fill_manual(values = c("Gold" = "gold", "Bronze" = "#cd7f32", "Silver" = "#C0C0C0"))

I am getting the following error message:

Error in class(grobs) <- "gList" :
attempt to set an attribute on NULL

Is there a quick way to solve this issue?

Alpha Value

Is there any way to utilize an Alpha level to change the transparency of images, similar to geom_point, etc. I cannot seem to find how this would be possible, but would be a wonderful feature to add if it does not yet exist.

ggbackground overrides annotation_custom

I want to use annotation_custom to add the logo to the plot. However, when I'm using it together with the ggbackground, the background image seems to cover the logos:

plot <- ggbackground(plot, "background.png")
plot + 
  annotation_custom(rasterGrob(logo), xmin = 0, xmax = 0.3, ymin = 0.3, ymax = -1) +
  coord_cartesian(clip = "off")

The same code without ggbackground(plot, "background.png") generates the expected result.

geom_phylopic and geom_pokemon "image not found" error is cryptic

When you try to plot a picture with a geom_phylopic or geom_pokemon layer and the reference does not exist, a cryptic error message appears: Error in class(grobs) <- "gList" : attempt to set an attribute on NULL. I think that this should be checked (I think a check for NULL will do) and a better error message should appear, given that will probably happen to people frequently. See example below:

ggplot(data.frame(poke="pikapika")) + geom_pokemon(aes(x=poke, y=poke, image=poke))

P.S. I found this when trying to build YuLab-SMU/treedata-book. There, the data in the phylopic section references the "name" of the species in phylopic, but geom_phylopic wants the reference to the "image".

EBImage dependency error when installing

I tried installing via install.packages("ggimage"). I also tried installing using install_github("GuangchuangYu/ggimage"). Both failed due to an "ERROR: dependency ‘EBImage’ is not available for package ‘ggimage’". I tried installing EBImage to resolve issue but it did not. Am I doing something wrong?

Control aspect ratio (or width & height) of images

It would be great to be able to adjust the aspect ratio or explicitly set the width/height instead of just a size parameter when plotting with geom_image.

For instance:
geom_image(aes(image=image), width = 0.5, height = 1)
geom_image(aes(image=image), aspect_ratio = 0.5)

geom_subview function

library(gtable)
library(ggplot2)
library(tidyr)
library(tibble)
library(ggimage)
library(ggrepel)

crime <- read.table("http://datasets.flowingdata.com/crimeRatesByState2005.tsv",
                  header=TRUE, sep="\t", stringsAsFactors=F)

plot_pie <- function(i) {
    df <- gather(crime[i,], type, value, murder:motor_vehicle_theft)
    ggplot(df, aes(x=1, value,fill=type)) +
        geom_col() + coord_polar(theta = 'y') +
        ggtitle(crime[i, "state"]) +
        theme_void() + theme_transparent() +
        theme(legend.position = "none",
              plot.title = element_text(size=rel(6), hjust=0.5))
}

crime <- as_data_frame(crime)

crime$pie <- lapply(1:nrow(crime), plot_pie)
radius <- sqrt(crime$population / pi)
radius <- radius/max(radius)

crime$width <- diff(range(crime$murder)) * 0.2 * radius
crime$height <- diff(range(crime$Robbery)) * 0.2 * radius

leg1 <- gtable_filter(
    ggplot_gtable(
        ggplot_build(plot_pie(1) + theme(legend.position="right"))
    ), "guide-box")


p <- ggplot(crime, aes(murder, Robbery)) + geom_subview(leg1, x=10, y=50) +
    geom_subview(crime$pie, crime$murder, crime$Robbery, width=crime$width, height=crime$height) +
    geom_text_repel(aes(label=state))

ggsave(p, file="bubble_pie.png")

bubble_pie

error with list.flag(), list.icon(), list.pokemon()

Get the following warning messages for functions list.flag(), list.icon() and list.pokemon()

list.flag()
character(0)
Warning message:
In readLines("https://github.com/behdad/region-flags/tree/gh-pages/png") :
incomplete final line found on 'https://github.com/behdad/region-flags/tree/gh-pages/png'
list.icon()
character(0)
Warning message:
In readLines(url) :
incomplete final line found on 'https://github.com/ionic-team/ionicons/tree/master/src/svg'
list.pokemon()
character(0)
Warning message:
In readLines(url) :
incomplete final line found on 'https://github.com/Templarian/slack-emoji-pokemon/tree/master/emojis'

Compatibility with ggplot 3.1.0

When I try to run the geom_image example in the vignette under R 3.5.1 ggplot 3.1.0, the color parameter does not work:

Warning: Ignoring unknown parameters: image_colour

When I downgrade ggplot to 3.0.0 the problem disappears.

line 86 > mistake

Dear GuangchuangYu
there is a little bit mistake:
Error in parse(outFile) :
/tmp/RtmpnV7Ck5/R.INSTALL2eb2d24f4f4/ggimage/R/geom_phylopic.R:86:8: unexpected '>'
85: }
86: ) |>

Using ggimage in package

Hi,
I intend to use ggimage in the next major version of cvms and have a question about the best way to include images in the package.

Currently, I have the svg files in /man/figures/ and have written the following function to find the absolute file path:

# Finds path of figure in either /man/figures/ or /help/figures/
# The latter being used in built packages
get_figure_path <- function(fig_name, pgk_name) {
  package_path <- system.file(package = pgk_name)
  for (sub in c("man", "help")) {
    fig_path <- paste0(package_path, "/", sub, "/figures/", fig_name)
    if (file.exists(fig_path))
      return(fig_path)
  }
  warning("Could not find figure.")
  invisible()
}

This seems to work, but I'm wondering if you see anything wrong/unsafe with this approach?

Thanks!

Online vigntte error: geom_icon()

Thanks for a fantastic package. The sample code for geom_icon in the online Vignette is not working for me. I get the following error:

"Error in class(grobs) <- "gList" : attempt to set an attribute on NULL"

I suspect the icon names ('ios-power', 'ios-wifi', 'ios-pie') in the code snippet are no longer available on https://ionicons.com/. If you change those to valid icon names, it works.

geom_image() changes aspect ratio arbitrarily

I am trying to insert a logo in my plot using geom_image(). The original logo is available here:
https://www.itvoice.in/wp-content/uploads/2016/12/zebronics_footer_logo.png
and looks like this:

When I make a ggplot using the code below, I get this image where the logo is shrunk along the x axis.

When I used reprex to make this post, the resulting logo was shrunk along Y axis. Neither of them is the correct rendition. I can't figure out what's going on here. I tried to play around with various parameters such as size and asp but I can't reproduce the original logo correctly.

library(ggplot2)
library(ggimage)

df <- data.frame(imglink = "https://www.itvoice.in/wp-content/uploads/2016/12/zebronics_footer_logo.png",
                 x = 1,
                 y = 1)

ggplot(df, aes(x = x, y = y, image = imglink)) +
  geom_image(size = 0.5) +
  theme_bw()

Created on 2020-03-07 by the reprex package (v0.3.0)

Modifying angle of geom_image

Hello! Is there any way of changing the angle of geom_image (without writing a new image at each angle)?

e.g.
ggplot(data, aes(x = x, y = y)) + geom_image(aes(image=image, angle=angle))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.