[英]Draw several plots at specified coordinates using annotation_custom()
我想將ggplot圖放置在地圖上的指定位置。 我選擇ggplot2
包,因為我更熟悉它,然后用grid
。 如果有人通過一個小例子幫助我,如何將grid
用於此類任務,那么我也將為您提供一個答案。
這是一個簡單的示例:
# create base plot
g <- ggplot(data.frame(x=c(-104,-94), y=c(33,38)), aes(x=x, y=y)) +
geom_blank()
# create theme
tm <- theme(axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
axis.line = element_blank(),
panel.background = element_blank(),
panel.grid = element_blank(),
panel.border = element_rect(color="grey", fill=NA),
title = element_text(size=5))
# create two plot which should be placed on the base plot
p1 <- ggplot(data.frame(x=c(-104,-94), y=c(33,38)), aes(x=x, y=y)) +
geom_point() + tm
p2 <- ggplot(data.frame(x=c(-100,-98), y=c(34,37)), aes(x=x, y=y)) +
geom_point() + tm
# place them using annotation_custom() function
a1 <- annotation_custom(grob = ggplotGrob(p1),
xmin = -104, xmax = -102,
ymin = 33, ymax = 35)
a2 <- annotation_custom(grob = ggplotGrob(p2),
xmin = -100, xmax = -98,
ymin = 35, ymax = 37)
# draw
g + a1
g + a2
g + a1 + a2
但是在g + a1 + a2
的情況下,我獲得的第一張圖片僅插入了第一張圖p1
。 怎么了? 如何使用annotation_custom()
繪制兩個或更多個圖?
我最近注意到這是一個奇怪的錯誤; 對於ggplot2認為相似的一些雜技,位置可以忽略不計,並且最終會疊加:
myGrob <- rectGrob(gp=gpar(fill="red", alpha=0.5), name="whatever")
myGrob2 <- rectGrob(gp=gpar(fill="blue", alpha=0.5))
# this is fine
qplot(1:10, 1:10) + theme(plot.margin=unit(c(0, 3, 0, 0), "cm")) +
annotation_custom(myGrob, xmin=5, xmax=6, ymin=3.5, ymax=5.5) +
annotation_custom(myGrob2, xmin=8, xmax=12, ymin=3.5, ymax=5.5)
# using twice the same grob, they just sit on top of each other
p <- qplot(1:10, 1:10) + theme(plot.margin=unit(c(0, 3, 0, 0), "cm")) +
annotation_custom(myGrob, xmin=5, xmax=6, ymin=3.5, ymax=5.5) +
annotation_custom(myGrob, xmin=8, xmax=12, ymin=3.5, ymax=5.5)
g <- ggplotGrob(p)
grid.ls(g$grobs[[4]]) # two of them
我不知道是什么原因造成的,但是大概與您的問題有關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.