在ggplot2图表下面注释

时间:2014-11-21 15:52:35

标签: r ggplot2

我想在ggplot2图表下方画一条线,上面有文字,如下所示:

enter image description here

可以指定x轴上基因的起点和终点。

到目前为止我的尝试:

require(ggplot2)
require(grid)
require(gridExtra)
data = data.frame(y = -log10(runif(100)), x = 1:100)
p = ggplot(data=data, aes(x, y)) + geom_point()
p = p + theme(plot.margin=unit(c(1, 1, 5, 1), "lines"))
t1 = textGrob("Gene1")
p1 = p + annotation_custom(grob=t1, xmin=0, ymin=0, xmax = 3, ymax=-.1)
print(p1)

给出:

enter image description here

如果我尝试通过调整ymax来向下移动文本,那么它就会消失。

2 个答案:

答案 0 :(得分:3)

你可以关闭剪辑,

g <- ggplotGrob(p1)
g$layout$clip[g$layout$name == "panel"] <- "off"
grid.newpage()
grid.draw(g)

答案 1 :(得分:3)

在我的回答中,我改变了一些事情: 1 - 我将数据名称更改为“df”,因为“数据”可能会导致对象和参数之间的混淆。 2 - 我删除了主数据图周围的额外面板空间,因此注释不是那么遥远。

require(ggplot2)
require(grid)
require(gridExtra)

# make the data
df <- data.frame(y = -log10(runif(100)), x = 1:100)

p <- ggplot(data=df, aes(x, y)) + geom_point()

# remove this line of code:
# p <- p + theme(plot.margin=unit(c(1, 1, 5, 1), "lines"))

# set up the plot theme for the annotation
blank_axes_and_thin_margin <- theme(axis.text = element_text(color="white"),
                    axis.title = element_text(color="white"),
                    axis.ticks = element_blank(),
                    panel.grid = element_blank(),
                    panel.border = element_blank(),
                    plot.margin=unit(c(0, 2, 0,2),"mm"))

# define the position of the arrow (you would change this part)
arrow_start <- min(df$x)
arrow_end <- mean(c(min(df$x), max(df$x)))
arrow_height <- 1

# here's the rectangle with the arrow
t2 <- ggplot(df, aes(x,y))+
  theme_bw()+
  geom_rect(aes(xmin=min(x), xmax = max(x)),
                ymin=0, ymax=4,fill="gray50")+
  coord_cartesian(ylim=c(0,4))+
  annotate(geom="text", label="Gene1", 
           x=20, y=2, size=6, color="black")+
  geom_segment(x=arrow_start, xend=arrow_end,
               y=arrow_height, yend=arrow_height, 
               color="black", arrow=arrow(ends="both"))+
  blank_axes_and_thin_margin
t2

# arrange the graphic objects here
# I use arrangeGrob because it allows you to use ggsave(), unlike grid.arrange
plot_both <- arrangeGrob(p, t2, nrow=2, heights=unit(c(0.75,0.25), "null"))
plot_both

# ta-da !

enter image description here