Tracy Campbell
Tracy Campbell

Reputation: 1

Adding table to one plot of facet_grid ggplot

I'm trying to add a table to the plotting region of one plot that is part of a larger facet_grid ggplot. My question is very similar to an earlier question, except I only want a plot on panel "A". Using the example data provided in the previous question:

library(lubridate)
library(ggplot2)
library(ggpmisc)

Date <- c("2010-01-28", "2010-02-28", "2010-03-28", 
          "2010-04-28", "2010-05-28", "2010-06-28", 
          "2010-07-28", "2010-08-28", "2010-09-28", 
          "2010-10-28")

Date <- as_date(Date)

Country <- rep("Japan", 10)
A <- runif(10, min=30, max=90)
B <- runif(10, min = 1, max = 15)


df <- data.frame(Date, Country, A, B)


df %>% pivot_longer(-c(Date, Country)) %>%
  ggplot(aes(x=Date,y=value,group=1,color=Country))+ 
  geom_line(size = 0.9) +
  facet_grid(name~Country, scales = "free", switch = "y") 

And then for my table, I have something similar to:

Time <- c("Today", "Yesterday", "One week ago")

Value_A <- 10:12

tableA <- data.frame(Time, Value_A)

I tried the answer provided in the previous question, using this edited version of their code:

d <- tibble(x = c(0.95, 0.95), y = c(0.95, 0.95),
            name = c("A"), tb = list(tableA))

df %>% pivot_longer(-c(Date, Country)) %>%
  ggplot(aes(x=Date,y=value,group=1,color=Country))+ 
  geom_line(size = 0.9) +
  geom_table_npc(data = d, aes(npcx = x, npcy = y, label = tb)) +
  facet_grid(name~Country, scales = "free", switch = "y") 

But I just get the same table repeating in both plots, panel A (top) and panel B (bottom). Any suggestions would be appreciated!

Upvotes: 0

Views: 19

Answers (0)

Related Questions