简体   繁体   中英

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

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

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM