如何将图像叠加到ggplot上?

时间:2012-09-28 04:52:45

标签: r png ggplot2

我想从网上阅读图片。 e.g。

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)

我该怎么做?

3 个答案:

答案 0 :(得分:19)

您正在寻找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()

enter image description here

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

答案 1 :(得分:4)

正确的解决方案是:

# 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)

答案 2 :(得分:2)

只需添加来自极好的Magick包的更新,它甚至可以将GIF覆盖在ggplot图像上:

           bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/font-awesome.css",
                      "~/Content/nprogress.css",
                      "~/Content/iCheck/flat/green.css",
                      "~/Content/daterangepicker.css",
                      "~/Content/bootstrap-dialog.css",
                      "~/Content/Tooltipster/css/tooltipster.css",
                      "~/Content/custom.css"));

            bundles.Add(new ScriptBundle("~/bundles/gentelella").Include(
                        "~/Scripts/fastclick.js",
                        "~/Scripts/nprogress.js",
                        "~/Scripts/jquery.icheck.js",
                        "~/Scripts/date.js",
                        "~/Scripts/moment-with-locales.js",
                        "~/Scripts/daterangepicker.js",
                        "~/Scripts/validator/validator.js",
                        "~/Scripts/bootstrap-dialog.js",
                        "~/Scripts/jquery.tooltipster.js",
                        "~/Scripts/custom.js"));