使用coord_cartesian时如何在绘图区域外添加文本?

时间:2017-06-19 03:19:15

标签: r ggplot2

我想在绘图区域的顶部添加一些文本(我的真实数据的p值)。这是一个例子和我尝试的内容:

数据:

library(tidyverse)

set.seed(123)
plt <- iris
plt$Petal.Width <- plt$Petal.Width + rnorm(nrow(plt))

plt.text <- plt %>% group_by(Species) %>% summarise(label = max(Petal.Width))

我为面板顶部的plt.text保留了sapce,但文字没有显示出来:

p <- ggplot(plt, aes(x= Species, y = Petal.Width)) +
    geom_violin() +
    geom_text(aes(x = Species, y = 4, label = label),
              data = plt.text, vjust = 0) +
    coord_cartesian(ylim = c(-2, 4), expand = 0) +
    theme(plot.margin = margin(0.2, 0.05, 0.05, 0.05, 'npc'))

enter image description here

关注this post后,我尝试了:

gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid::grid.draw(gt)

enter image description here

您可以看到虽然正确显示了文字,但在上图中也完整显示了小提琴曲线图。我怎样才能只在剧情区域外显示文字并保持小提琴情节的转换?

2 个答案:

答案 0 :(得分:2)

您还可以尝试facet_grid方法

library(tidyverse)
ggplot(plt, aes(x= Species, y = Petal.Width)) +
  geom_violin() +
  facet_grid(~Species, scales = "free_x", labeller = 
               labeller(Species =set_names(as.character(plt.text$label), plt.text$Species))) +
  theme_minimal(base_size = 14) + 
  theme(panel.background = element_rect(fill = "lightgrey", color="lightgrey"),
        panel.spacing.x =unit(0, "cm"))

enter image description here

答案 1 :(得分:1)

我使用cowplot做了什么:

p <- ggplot(plt, aes(x= Species, y = Petal.Width)) +
    geom_violin() +
    coord_cartesian(ylim = c(-2, 4), expand = 0) +
    theme_grey()
ann <- ggplot(plt.text, aes(x = Species, y = 0, label =label)) +
    geom_text() +
    theme_void()


library(cowplot)
plot_grid(ann, p, ncol = 1, rel_heights = c(.05, 1), align = 'v')