This question is related to Can geom_image() from the ggimage package be made to preserve the image aspect ratio? but in my application I want to make a scatterplot, using images scaled in proportion to their actual image sizes.
The figure (done manually, with PPT) I want to reproduce with geom_image()
is shown here:
I read the data as follows, and get the image sizes using readPNG()
in the png
package:
> brains.dat <- file.path(folder, "brain-size.csv")
> brains <- read.csv(brains.dat, stringsAsFactors=FALSE)
> brains$class <- factor(brains$class)
>
> library(png)
>
> sizes <- t(sapply(brains$img, function(x) dim(readPNG(x))))
> brains$height <- sizes[,1]
> brains$width <- sizes[,2]
> brains
species class brain_weight neurons img height width
1 Capybara non-primate 48.2 0.30 capybara.png 31 70
2 Rhesus Macaque primate 69.9 1.71 rhesus.png 63 75
3 Western Gorilla primate 377.0 9.10 gorilla.png 71 95
4 Human primate 1232.0 16.30 human.png 98 117
5 African Bush Elephant non-primate 2848.0 5.59 elephant.png 98 168
>
I don't see any way to set the height and width of each image in the call below to geom_image()
:
library(ggimage)
library(ggplot2)
col <- ifelse(brains$class=="primate", "blue", "red")
ggplot(brains, aes(x=brain_weight, y=neurons)) +
geom_text(aes(label=species), color=col, hjust="inward") +
geom_image(aes(image=img)) + theme_bw()
What I get from this makes all images about the same size, in width I think. I'm ignoring the tweaks needed to position the labels better.
Edit: This was filed as an issue, https://github.com/GuangchuangYu/ggimage/issues/6. The author says this is not yet supported, but perhaps there is a workaround?