首页 > 解决方案 > 在直方图的背景中添加图像

问题描述

我正在尝试将图像添加到直方图的背景中。我开始使用 R 并且我从 ggplot2 指南的最后一点有了这个想法:http: //r-statistics.co/Complete-Ggplot2-Tutorial-Part2-Customizing-Theme-With-R-Code.html

这是我正在使用的代码

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

这是我得到的错误:

Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = c(7L, 4L, 1L, 4L,  : 
  replacement has 415 rows, data has 1

我想问题在于图像的大小。我还在学习R的基础,如果这个问题的答案太简单,请见谅。

谢谢。

标签: rggplot2plot

解决方案


因为我不能使用你的数据,所以我只是使用了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) 

如果由于某种原因图像的一部分超出了绘图范围,请使用expand_limits更大的绘图范围。

希望这可以帮助。


推荐阅读