R 在直方图的背景中添加图像

R 在直方图的背景中添加图像,r,ggplot2,plot,R,Ggplot2,Plot,我正在尝试将图像添加到直方图的背景中。我开始使用R,从本指南关于ggplot2的最后一点开始我就有了这个想法: 这是我正在使用的代码 library(ggplot2) **library(grid) library(png) img<- png::readPNG("logo.png") g_pic<- rasterGrob(img, interpolate=TRUE)** ggplot(Ruta1600, aes(x=Ruta1600$fvec_aprox_md, fill=Ru

我正在尝试将图像添加到直方图的背景中。我开始使用R,从本指南关于ggplot2的最后一点开始我就有了这个想法:

这是我正在使用的代码

library(ggplot2) 
**library(grid)
library(png)
img<- png::readPNG("logo.png")
g_pic<- rasterGrob(img,  interpolate=TRUE)**
ggplot(Ruta1600, aes(x=Ruta1600$fvec_aprox_md, fill=Ruta1600$nivel_dif_exp_codigo)) +
  geom_histogram() +
  labs(x="fvec_aprox_md", y="Count") +
  xlim(c(0,3000)) +
  facet_grid(Ruta1600$nivel_dif_exp_codigo~Ruta1600$fh_natural_id)    +
  geom_vline(aes(xintercept=mean(Ruta1600$fvec_aprox_md)),color="black", linetype="dashed", size=1) +
  **annotation_custom(g_pic, xmin=5, xmax=7, ymin=30, ymax=45)**
库(ggplot2)
**图书馆(网格)
图书馆(png)

img因为我不能使用你的数据,所以我只使用了
iris
数据。我试着使用你添加到情节中的所有东西。使用下面的代码,我没有得到任何错误

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

# location is relative to the work directory
img <- readPNG("./test/Rlogo.png")
g_pic <- rasterGrob(image = img,
                    interpolate = TRUE)

ggplot(data = iris,
       aes(x = Petal.Length,
           fill = Species)) +
  # place first, to make sure it is in the background
  annotation_custom(grob = g_pic,
                    xmin = 3,
                    xmax = 5,
                    ymin = 5,
                    ymax = 10) +
  # the histogram
  geom_histogram() +
  # the mean lines
  geom_vline(aes(xintercept = mean(Petal.Length)),
             color = "black", 
             linetype = "dashed", 
             size = 1) +
  # faceting
  facet_wrap(~ Species) 
库(ggplot2)
图书馆(网格)
图书馆(png)
#位置相对于工作目录

img我们不能使用代码,因为您没有提供示例的数据。能给我们提供数据吗?请使用
dput(Ruta1600)
或者如果它真的很大
dput(head(Ruta1600,20))
。无需使用
$
ggplot
中选择变量。您可以不使用
Ruta1600$
cowplot
软件包具有很好的功能,用于在绘图上注释图像。查看@ricoderks谢谢你的建议!不幸的是,我不能分享我正在使用的数据,但我想如果你能给我一个简单的例子,我可以这样做me@JanBoyer非常感谢你!Cowplot似乎非常有用,我会尝试使用它非常感谢你,这对我来说非常有用!!感谢您抽出时间回答!
library(ggplot2)
library(grid)
library(png)

# location is relative to the work directory
img <- readPNG("./test/Rlogo.png")
g_pic <- rasterGrob(image = img,
                    interpolate = TRUE)

ggplot(data = iris,
       aes(x = Petal.Length,
           fill = Species)) +
  # place first, to make sure it is in the background
  annotation_custom(grob = g_pic,
                    xmin = 3,
                    xmax = 5,
                    ymin = 5,
                    ymax = 10) +
  # the histogram
  geom_histogram() +
  # the mean lines
  geom_vline(aes(xintercept = mean(Petal.Length)),
             color = "black", 
             linetype = "dashed", 
             size = 1) +
  # faceting
  facet_wrap(~ Species)