r - 在直方图的背景中添加图像
问题描述
我正在尝试将图像添加到直方图的背景中。我开始使用 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的基础,如果这个问题的答案太简单,请见谅。
谢谢。
解决方案
因为我不能使用你的数据,所以我只是使用了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
更大的绘图范围。
希望这可以帮助。
推荐阅读
- java - 如何在 Java 中使用 assert 来拒绝非 String 参数?
- ios - 如何将单个类记录中的所有属性值显示到 TableView 中
- angular - 将 asp.net core angular 应用程序部署到 iis
- vba - 从命令按钮 VBA 获取值
- python - 如何使用底图在 Python 中绘制 GIS 数据库?
- javascript - 为什么 Ajax $.post() 函数返回数据
? - java - 初始化时继承的类变量会覆盖父级设置的自己的值
- perforce - Perforce 流复制想要删除文件
- android - Android - Mockito 无法模拟此类:class android.content.Context
- python - Scrapy不返回元素