mt1022
mt1022

Reputation: 17299

How to add text outside plot region when coord_cartesian is used?

I want to add some text (p values for my real data) on the top of the plot region. Here is a example and what I tried:

data:

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))

I reserved sapce for the plt.text on the top of the panel, but the text didn't show up:

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

Following this post, I tried:

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

enter image description here

You can see although the text is correctly displayed, the trancated violin plot is also shown in full in the above plot. How can I only show the text outside the plot region and still keep the violin plot trancated?

Upvotes: 1

Views: 2583

Answers (2)

Roman
Roman

Reputation: 17648

You can also try a facet_grid approach

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

Upvotes: 3

GGamba
GGamba

Reputation: 13680

What I'd do, using 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')

Upvotes: 1

Related Questions