【问题标题】:How do I overlay an image on to a ggplot?如何将图像叠加到 ggplot 上?
【发布时间】:2012-09-19 23:17:00
【问题描述】:

我想从网上阅读一张图片。例如

http://api.altmetric.com/donut/502878_64x64.png

并将其插入ggplot的右上角

df <- data.frame(x=1:10, y=sample(1:100,10))
# a fake plot to try it on.
ggplot(df, aes(x,y)) + geom_point(size = 2)

我该怎么做?

【问题讨论】:

  • annotation_raster。查看示例here
  • 谢谢@mnel!我仍然需要能够从 URL 中读取此图像

标签: r png ggplot2


【解决方案1】:

您正在寻找annotation_rasterreadPNG

mypngfile <- download.file('http://api.altmetric.com/donut/502878_64x64.png', destfile = 'mypng.png', mode = 'wb')
library(png)
mypng <- readPNG('mypng.png')


p <- qplot(mpg, wt, data = mtcars) + theme_bw()
p + annotation_raster(mypng, ymin = 4.5,ymax= 5,xmin = 30,xmax = 35) + 
    geom_point()

这些新功能(以及更多示例)描述为here

【讨论】:

    【解决方案2】:

    正确的解决方案是这样的:

    # This was one of my issues, reading a png from the web
    my_image <-  readPNG(getURLContent('http://path.to/image.png'))
    p1 + annotation_raster(my_image, ymin = 4,ymax= 5,xmin = 30,xmax = 40)
    

    【讨论】:

      【解决方案3】:

      只需从很棒的包 Magick 添加更新,它甚至可以让 GIF 覆盖在 ggplot 图像上:

      library(ggplot2)
      library(magick)
      library(here) # For making the script run without a wd
      library(magrittr) # For piping the logo
      
      # Make a simple plot and save it
      ggplot(mpg, aes(displ, hwy, colour = class)) + 
        geom_point() + 
        ggtitle("Cars") +
        ggsave(filename = paste0(here("/"), last_plot()$labels$title, ".png"),
               width = 5, height = 4, dpi = 300)
      
      # Call back the plot
      # Now call back the plot
      background <- image_read(paste0(here("/"), "Cars.png"))
      # And bring in a logo
      logo_raw <- image_read("https://i.imgur.com/e1IneGq.jpg") 
      
      frames <- lapply(logo_raw, function(frame) {
        image_composite(background, frame, offset = "+70+800")
      })
      
      animation <- image_animate(image_join(frames))
      
      image_write(animation, "~/Cars_Travolta.gif")
      

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 2021-10-21
        • 1970-01-01
        • 2011-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多