这是让你前进的东西(归功于我改编的 this 答案)。
我们使用annotate 将您的labels 绘制在两个不同的x 轴坐标上,这将用作我们的标签(因此我们需要关闭theme 中的实际标签)。
首先,我们创建两个向量,其中包含我们想要的不同颜色的确切标签。
dat <- data.frame(x = c(1,2,3,4,5,6), y = c(2,3,4,6,2,3))
breaks <- c(3,5)
labels_new1 <- c(NA, NA, 3, NA, 5, NA) # NA in order to skip that annotation
labels_new2 <- c(NA, NA, "(0.3)", NA, "(0.5)", NA)
重要部分:
coord_cartesian(xlim = c(0, 6), expand = FALSE) + # this will cut our plot properly
plot.margin = unit(c(1, 1, 1, 5), "lines") # this will give us some space on the left
请注意,在coord_cartesian 的定义中,我们实际上切断了两个注释(请注意,您在下一部分中看到的两个 x 值 (-1, -0.5) 超出了xlim 范围)。
绘图对象:
g1 <- ggplot() +
geom_point(data = dat, aes(x = x, y = y)) +
annotate(geom = "text", y = seq_len(nrow(dat)), x = -1, label = labels_new1, size = 4) +
#first the number add color = "blue" for example
annotate(geom = "text", y = seq_len(nrow(dat)), x = -0.5, label = labels_new2, size = 4, color = "red") +
#second the parenthesis (colored in red)
coord_cartesian(xlim = c(0, 6), expand = FALSE) +
scale_y_continuous(breaks = breaks) +
#now lets shut off the labels and give us some left space in the plot
theme(plot.margin = unit(c(1, 1, 1, 5), "lines"),
axis.title.y = element_blank(),
axis.text.y = element_blank())
最后:
g2 <- ggplot_gtable(ggplot_build(g1)) # convert to grob
g2$layout$clip[g2$layout$name == "panel"] <- "off" # clipping of the axes
# this will show the two annotations that we left off before
grid::grid.draw(g2)
备注:
您可以使用x=-1 和x=-0.5 来移动两个注释,并使用c(1, 1, 1, 5) 中的最后一个值来为左侧留出更多空间。
labels_new1 和labels_new2 非常重要,他们正在做所有繁重的工作 what 和 where 你想展示一些东西。