【问题标题】:Draw several plots at specified coordinates using annotation_custom()使用 annotation_custom() 在指定坐标处绘制多个图
【发布时间】:2013-07-22 06:02:05
【问题描述】:

我想将 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()绘制两个以上的图?

【问题讨论】:

  • 一种解决方法是将 grobs 包装在 gTreeg1 = grobTree(ggplotGrob(p1)) ; g2 = grobTree(ggplotGrob(p2)) 中,并在 annotation_custom 中使用这些 grobs。不要问我为什么!
  • 请参阅github.com/hadley/ggplot2/issues/817 了解有关此问题的讨论。不过,ggplot2 dev 已经停止了一段时间,因此可能无法快速响应该问题。

标签: r ggplot2


【解决方案1】:

这是我最近注意到的一个奇怪的错误;对于 ggplot2 认为相似的一些 grobs,可以忽略该位置,它们最终会叠加:

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

我不知道是什么原因造成的,但大概与您的问题有关。

【讨论】:

  • 嗨,巴蒂斯特。这个问题看起来与 #817 不同,尽管可能相关。甚至可能是相同的潜在错误。无论如何,我建议您将其作为单独的问题报告。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
相关资源
最近更新 更多