I am using flextable to produce tables in PDF output from rmarkdown. I faced with some issues after I knitted the code.
First: When I add a background color to the first header row, the background colors of the second header row just below are not the same length as the upper one.
Second: I am merging two header rows, after the merge, white lines appear.
Third: I created a Sparkline column with gg_chunk and used both line graph and point graph. The points which are located at the the top and bottom are cut off in the column.
This is how my output looks like:
Here is the reproducible code example of my problem:
library(purr)
library(ggplot2)
z <- as.data.table(iris)
z <- z[c(1:5, 51:55, 101:105),]
dataset_gg <- z %>%
select(Sepal.Length, Species) %>%
nest(Sepal.Length)
#This function is for the sparkline
gg <- function(x) {
d <- x %>%
mutate(x = row_number()) %>%
rename(y = 1)
ggplot(d) +
geom_line(aes(x, y), size = 0.2) +
geom_point(aes(x, y), colour = ifelse(x == max(x),'red','black'), size = 0.7) +
theme_void()
}
dataset_gg <- dataset_gg %>%
mutate(Trend = purrr::map(data, ~ gg(.x)))
z <- left_join(z, dataset_gg, by = "Species")
ft <- flextable(z,
col_keys = c("Species", "Sepal.Length", "Petal.Length", "Sepal.Width", "Petal.Width", "Trend"))
#For header merge
header.df <- data.frame(
col_keys = c("Species", "Sepal.Length", "Petal.Length", "Sepal.Width", "Petal.Width", "Trend"),
line1 = c("Species", rep("Length", 2), rep("Width", 2), ""),
line2 = c("Species", "Sepal.Length", "Petal.Length", "Sepal.Width", "Petal.Width", "Trend")
)
ft <- set_header_df(ft,
mapping = header.df,
key = "col_keys"
)
ft <- merge_h(ft, part = "header")
ft <- merge_v(ft, j = "Species", part = "header")
ft <- theme_zebra(ft)
ft <- flextable::align(ft, align = "center", part = "header")
ft <- flextable::width(ft, width = 1.2, unit = "in")
ft <- add_header_row(ft, values = "*Footnote", top = TRUE, colwidths = 6)
ft <- bg(ft, i = 1, bg = "#839098", part = "header")
ft <- bg(x = ft, i = 2:3, bg = "#EA763B", part = "header")
ft <- flextable::compose(ft, j = "Trend", value = as_paragraph(
gg_chunk(value = Trend, width = 15, height = 6.5, unit = "mm")))
ft
