1

我正在制作一大堆大小变化的图表。我希望每个图表在图表边距(顶部 y 轴值)的特定点上显示一个符号(例如星号),而不管绘图大小。现在我通过为 each 定义 x/y 来手动完成textGrob,但必须有更好的方法。

绘图大小由数据集中的类别数量决定(下面的玩具数据)。理想情况下,输出图将具有相同的面板尺寸(我假设可以通过以英寸为单位定义边距尺寸并将该值添加到height参数中来控制?)。宽度通常不会改变,但最好根据定义的设备宽度(和绘图边距)自动化 x 和 y 放置。

非常感谢!

library(ggplot2)
library(gridExtra)

set.seed(123)
df <- data.frame(x = rnorm(20, 0, 1), y = rnorm(20, 0, 1), category = rep(c("a", "b"), each = 10))

## plot 1
sub <- df[df$category == "a",]
height = 2*length(unique(sub$category))
p <- ggplot(sub) + 
    geom_point(aes(x = x, y = y)) +
    facet_grid(category ~ .) 


jpeg(filename = "fig1.jpg",
     width = 6, height = height, units = "in", pointsize = 12, res = 900,
     quality = 100)
g <- arrangeGrob(p, sub = textGrob("*", x = 0.07, y = 10.15, hjust = 0, vjust=0,   #### puts the top discharge value; might need to be adjusted manually in following years
    gp = gpar(fontsize = 15)))
grid.draw(g)
dev.off()



 ## plot 2

height = 2*length(unique(df$category))
p <- ggplot(df) + 
    geom_point(aes(x = x, y = y)) +
    facet_grid(category ~ .)

jpeg(filename = "fig2.jpg",
     width = 6, height = height, units = "in", pointsize = 12, res = 900,
     quality = 100)
g <- arrangeGrob(p, sub = textGrob("*", x = 0.07, y = 23.1, hjust = 0, vjust=0,   #### puts the top discharge value; might need to be adjusted manually in following years
    gp = gpar(fontsize = 15)))
grid.draw(g)
dev.off()
4

0 回答 0