Trying to add an image to a polar plot gives "Error: annotation_custom only works with Cartesian coordinates"
Asked Answered
B

1

3

I've tried to follow the answer's given already for adding images to plots, but they do not work when using coord_polar()

# install.packages("RCurl", dependencies = TRUE)
library(RCurl)
myurl <- "http://vignette2.wikia.nocookie.net/micronations/images/5/50/German_flag.png"

# install.packages("png", dependencies = TRUE)
library(png)
img <-  readPNG(getURLContent(myurl))

# install.packages("ggplot2", dependencies = TRUE)
library(ggplot2)

ger <- grid::rasterGrob(img, interpolate=TRUE)

## works, adds the image to the plot
ggplot(mtcars, aes(x=mpg, y= cyl)) + geom_line() + annotation_custom(ger, 10, 15, 5)

## doesn't work
ggplot(mtcars, aes(x=mpg, y= cyl)) + geom_line() + annotation_custom(ger) + coord_polar()
> Error: annotation_custom only works with Cartesian coordinates

Ideally I'd like to be able to position the flag image within the center of the polar plot, and another image along the y-axis.

Is there anyway to add the image? It can be as-is, no transformation required.

I'm using ggplot2 version 2.0

Brammer answered 28/12, 2015 at 15:11 Comment(4)
It's more likely that we will be able to help you if you make a minimal reproducible example to go along with your question (what is ex?).Cautery
Typo sorry, ex is mtcarsBrammer
Do you want the images to be transformed from cartesian to polar coordinates as well? Or do you want the image, as-is, to be added to the top of the polar plot? If the latter, the cowplot package might do what you need.Akim
The image to be as-is. I'll add to question, thanksBrammer
B
5

Gregor's suggestion for using the cowplot library has got me there.

Following the introduction to cowplot you can use the draw_grob function to overlay images as you like. It takes a bit of tweaking as the position changes depending on the dimensions of the plot, but its possible.

Example:

# install.packages("RCurl", dependencies = TRUE)
library(RCurl)
myurl <- "http://vignette2.wikia.nocookie.net/micronations/images/5/50/German_flag.png"

# install.packages("png", dependencies = TRUE)
library(png)
img <-  readPNG(getURLContent(myurl))

# install.packages("ggplot2", dependencies = TRUE)
library(ggplot2)

ger <- grid::rasterGrob(img, interpolate=TRUE)

g <- ggplot(mtcars, aes(x=mpg, y= cyl)) + geom_line() + coord_polar()

# install.packages("cowplot", dependencies = TRUE)
library(cowplot)
h <- ggdraw(g)
## tweak this to fit your plot
h + draw_grob(ger, 0.4, 0.48, 0.07, 0.07)

enter image description here

Brammer answered 29/12, 2015 at 8:43 Comment(1)
Draw_grob does nothing more than calling annotation_custom: > draw_grob function (grob, x = 0, y = 0, width = 1, height = 1) { annotation_custom(grid::grobTree(grob), xmin = x, xmax = x + width, ymin = y, ymax = y + height) } <environment: namespace:cowplot> it also fails when plotting on a ggmapPremaxilla

© 2022 - 2024 — McMap. All rights reserved.