Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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

like image 214
MarkeD Avatar asked Nov 16 '25 08:11

MarkeD


1 Answers

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

like image 123
MarkeD Avatar answered Nov 18 '25 22:11

MarkeD