将函数转换为ggplot函数

时间:2015-09-16 16:17:05

标签: r ggplot2

基本上我想编写一个以典型的ggplot方式工作的函数,你只需添加"添加"它使用+运算符。我现在所拥有的是:

为了使这个可重复,我将以下图像作为png保存到我的工作目录中,并使用mtcars作为绘图数据。

https://en.wikipedia.org/wiki/File:Chevypnglogo.png

library(png)
library(ggplot2)
library(grid)

logo <- readPNG(
  source = 'Chevypnglogo.png'
)
logo_grob <- rasterGrob(logo, interpolate = TRUE)
add_logo <- function(g, logo) {
  y.range <- ggplot_build(g)$panel$ranges[[1]]$y.range
  y.space <- (y.range[2] - y.range[1]) / 100
  height <- (y.range[2] - y.range[1]) / 10

  x.range <- ggplot_build(g)$panel$ranges[[1]]$x.range
  x.space <- (x.range[2] - x.range[1]) / 100
  width <- (x.range[2] - x.range[1]) / 10

  g <- g + annotation_custom(
    logo, 
    xmin = x.range[1] + x.space, xmax = x.range[1] + width,
    ymin = y.range[2] - height, ymax = y.range[2] - y.space
  )
}

test.plot <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point()
test.plot <- add_logo(test.plot, logo_grob)

我真正希望能做的是:

test.plot <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  add_logo(logo_grob)

有人知道如何更改我的代码以使其成为可能吗?

1 个答案:

答案 0 :(得分:0)

#How about:

#Test data
logo <- readPNG(source = 'Chevypnglogo.png')
logo_grob <- rasterGrob(logo, interpolate=T)

#The function
add_logo <- function(g, logo) {

  y.range  <- ggplot_build(g)$panel$ranges[[1]]$y.range
  y.space  <- (y.range[2] - y.range[1]) / 100
  height   <- (y.range[2] - y.range[1]) / 10

  x.range <- ggplot_build(g)$panel$ranges[[1]]$x.range
  x.space <- (x.range[2] - x.range[1]) / 100
  width <- (x.range[2] - x.range[1]) / 10

  #Create annotation and wrap it in list()
  my_anot <- list(annotation_custom(logo, 
                  xmin = x.range[1] + x.space, xmax = x.range[1] + width,
                  ymin = y.range[2] - height, ymax = y.range[2] - y.space))
  return(my_anot)
}

#Test
test.plot <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
test.plot <- test.plot + add_logo(g=test.plot, logo_grob)