In line plot using R spec_plot not working

45 Views Asked by At

I am strugling with spec_plot() in a tbl kable, example in the code below. When I try to add the inline plot in the column "chart" of the table, it returns the error Error: x must be a string of length 1. I don't know what I am doing wrong. Does anyone could help me with this?

library(tidyverse)
library(stringr)

tbl.example =  cbind(paste0("G", c(1,2,1,1,2,1,1,1,2,3)), 
                                   rownames(mtcars[1:10,]), 
                                   mtcars[1:10,] %>% select(mpg)) %>% 
  rename(groups = "paste0(\"G\", c(1, 2, 1, 1, 2, 1, 1, 1, 2, 3))",
         cars = "rownames(mtcars[1:10, ])" )

tbl.example = tbl.example %>% 
  mutate(cars = stringr::word(cars, 1)) %>% 
  spread(groups, mpg)

tbl.example[is.na(tbl.example)] <- 10

tbl.chart <- split(tbl.example[,2:4], f = tbl.example$cars)

tbl <- tbl.example %>% mutate(chart = "")

tbl %>% 
  kable(booktabs = T, longtable = T, align = 'l', linesep = "\\addlinespace") %>%
  kable_styling(latex_options = c("HOLD_position", 'repeat_header')) %>% 
  row_spec(0, bold = T) %>%
  column_spec(1, bold = F, border_right = T) %>%
  column_spec(ncol(tbl), image = spec_plot(tbl.chart, polymin = 5))
1

There are 1 best solutions below

3
Suzy On

I changed the structure of the "tbl.chart" and it worked! See code below.

The trick was to have each line of the main table as a column in the tbl.chart. Now the minigraphs are working perfectly.

library(tidyverse)
library(stringr)

tbl.example =  cbind(paste0("G", c(1,2,1,1,2,1,1,1,2,3)), 
                                   rownames(mtcars[1:10,]), 
                                   mtcars[1:10,] %>% select(mpg)) %>% 
  rename(groups = "paste0(\"G\", c(1, 2, 1, 1, 2, 1, 1, 1, 2, 3))",
         cars = "rownames(mtcars[1:10, ])" )

tbl.example0 = tbl.example %>% 
  mutate(cars = stringr::word(cars, 1)) 

tbl.example = tbl.example0 %>% spread(groups, mpg)
tbl.chart <- tbl.example0 %>% spread(cars, mpg)

tbl.example[is.na(tbl.example)] <- 10
tbl.chart[is.na(tbl.chart)] <- 10

tbl <- tbl.example %>% mutate(chart = "")

tbl %>% 
  kable(booktabs = T, longtable = T, align = 'l', linesep = "\\addlinespace") %>%
  kable_styling(latex_options = c("HOLD_position", 'repeat_header')) %>% 
  row_spec(0, bold = T) %>%
  column_spec(5, image = spec_plot(tbl.chart[,2:7], polymin = 5))