使用markdown,rstudio和knitr对齐表格中的图像 [英] Alignment of images in tables with markdown, rstudio and knitr

查看:110
本文介绍了使用markdown,rstudio和knitr对齐表格中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Rstudio创建以PDF格式工作的标准月度报告,我想将ggplot输出与一张表格合并在一起-一个新的图表,每行每个单元格一个.我是Markdown,乳胶,Pandoc和Knitr的新手,所以对我来说这是个雷区.

I'm trying to create a standard monthly report for work in PDF format using Rstudio and I want to incorporate ggplot output with a table of figures - a new chart, one per cell on each row. I'm new to markdown, latex, pandoc and knitr so this is a bit of minefield for me.

我发现了如何使用kable插入图表,但是图像与同一行上的文本不对齐.

I have found out how to insert the charts using kable but the images are not aligned with the text on the same row.

我在问题的底部使用了虚拟数据放置了一些(rstudio markdown)代码,下面是一些图像,这些图像显示了我正在尝试做的事情和遇到的问题

I've put some (rstudio markdown) code using dummy data at the bottom of my question, and here are some images showing what I'm trying to do and the problem I've got

我想合并到表格中的图形示例

表格和未对齐的文字和图像都是这样的

您可以看到文本和图像未对齐.如果我将图像放在外面的话,桌子就好又紧凑,将图像放进去就意味着桌子分散在多页上,即使这些图像本身并不高.

You can see that the text and the images are not aligned. If I leave the images out the tables are nice and compact, putting the images in means the tables spread out over multiple pages, even though the images themselves aren't that tall.

欢迎提出任何建议-代码段就这样加倍.

Any advice welcome - code snippets doubly so.

非常感谢

  title: "Untitled"
  output: pdf_document
  ---

  This example highlights the issue I'm having with formatting a nice table with the graphics and the vertical alignment of text.



  ```{r echo=FALSE, results='hide', warning=FALSE, message=FALSE}
    ## Load modules
    library(dplyr)
    library(tidyr)
    library(ggplot2)

    ## Create a local function to plot the z score
    varianceChart <- function(df, personNumber) {
      plot <- df %>%
        filter(n == personNumber) %>%
        ggplot() +
        aes(x=zscore, y=0) +
        geom_rect(aes(xmin=-3.32, xmax=-1.96, ymin=-1, ymax=1), fill="orange2", alpha=0.8) + 
        geom_rect(aes(xmin=1.96, xmax=3.32, ymin=-1, ymax=1), fill="olivedrab3", alpha=0.8) +
        geom_rect(aes(xmin=min(-4, zscore), xmax=-3.32, ymin=-1, ymax=1), fill="orangered3") + 
        geom_rect(aes(xmin=3.32, xmax=max(4, zscore), ymin=-1, ymax=1), fill="chartreuse4") +
        theme(axis.title = element_blank(), 
              axis.ticks = element_blank(), 
              axis.text = element_blank(),
              panel.grid.minor = element_blank(),
              panel.grid.major = element_blank()) +
        geom_vline(xintercept=0, colour="black", alpha=0.3) +
        geom_point(size=15, shape=4, fill="lightblue") ##Cross looks better than diamond

      return(plot)
    }

    ## Create dummy data
    Person1 <- rnorm(1, mean=10, sd=2) 
    Person2 <- rnorm(1, mean=10, sd=2)
    Person3 <- rnorm(1, mean=10, sd=2)
    Person4 <- rnorm(1, mean=10, sd=2) 
    Person5 <- rnorm(1, mean=10, sd=2) 
    Person6 <- rnorm(1, mean=6,  sd=1) 

    ## Add to data frame
    df <- data.frame(Person1, Person2, Person3, Person4, Person5, Person6)

    ## Bring all samples into one column and then calculate stats
    df2 <- df %>% 
      gather(key=Person, value=time)

    mean <- mean(df2$time)
    sd   <- sqrt(var(df2$time))

    stats <- df2 %>%
      mutate(n = row_number()) %>%
      group_by(Person) %>%
      mutate(zscore = (time - mean) / sd)

    graph_directory <- getwd() #'./Graphs'

    ## Now to cycle through each Person and create a graph
    for(i in seq(1, nrow(stats))) {
      print(i)
      varianceChart(stats, i)

      ggsave(sprintf("%s/%s.png", graph_directory, i), plot=last_plot(), units="mm", width=50, height=10, dpi=1200)
    }

    ## add a markup reference to this dataframe
    stats$varianceChart <- sprintf('![](%s/%s.png)', graph_directory, stats$n)  

    df.table <- stats[, c(1,2,5)]
    colnames(df.table) <- c("Person Name", "Time taken", "Variance Chart")
  ```


  ```{r}  
    library(knitr)
    kable(df.table[, c(1,2)], caption="Rows look neat and a sensible distance apart")
    kable(df.table, caption="Rows are separated a long way apart and images and text are misaligned")

  ```

推荐答案

或者您使用\raisebox.它将内容放入新框内,并使用其参数可以修改框的偏移量(播放当前设置为-0.4的参数):

Or you make use of \raisebox. It puts the content inside of a new box and with its parameters you can modify the offset of the box (play around with the parameter currently set to -0.4):

---
title: "Untitled"
output: pdf_document
---

This example highlights the issue I am having with formatting a nice table with the graphics and the vertical alignment of text.

```{r echo=FALSE, results='hide', warning=FALSE, message=FALSE}
## Load modules
library(dplyr)
library(tidyr)
library(ggplot2)

## Create a local function to plot the z score
varianceChart <- function(df, personNumber) {
  plot <- df %>%
             filter(n == personNumber) %>%
             ggplot() +
             aes(x=zscore, y=0) +
             geom_rect(aes(xmin=-3.32, xmax=-1.96, ymin=-1, ymax=1), fill="orange2", alpha=0.8) + 
             geom_rect(aes(xmin=1.96, xmax=3.32, ymin=-1, ymax=1), fill="olivedrab3", alpha=0.8) +
             geom_rect(aes(xmin=min(-4, zscore), xmax=-3.32, ymin=-1, ymax=1), fill="orangered3") + 
             geom_rect(aes(xmin=3.32, xmax=max(4, zscore), ymin=-1, ymax=1), fill="chartreuse4") +
             theme(axis.title = element_blank(), 
                   axis.ticks = element_blank(), 
                   axis.text = element_blank(),
                   panel.grid.minor = element_blank(),
                   panel.grid.major = element_blank()) +
                   geom_vline(xintercept=0, colour="black", alpha=0.3) +
                   geom_point(size=15, shape=4, fill="lightblue") ##Cross looks better than diamond
  return(plot)
}

## Create dummy data
Person1 <- rnorm(1, mean=10, sd=2) 
Person2 <- rnorm(1, mean=10, sd=2)
Person3 <- rnorm(1, mean=10, sd=2)
Person4 <- rnorm(1, mean=10, sd=2) 
Person5 <- rnorm(1, mean=10, sd=2) 
Person6 <- rnorm(1, mean=6,  sd=1) 

## Add to data frame
df <- data.frame(Person1, Person2, Person3, Person4, Person5, Person6)

## Bring all samples into one column and then calculate stats
df2  <- df %>% gather(key=Person, value=time)
mean <- mean(df2$time)
sd   <- sqrt(var(df2$time))

stats <- df2 %>%
             mutate(n = row_number()) %>%
             group_by(Person) %>%
             mutate(zscore = (time - mean) / sd)

graph_directory <- getwd() #'./Graphs'

## Now to cycle through each Person and create a graph
for(i in seq(1, nrow(stats))) {
  print(i)
  varianceChart(stats, i)

  ggsave(sprintf("%s/%s.png", graph_directory, i), plot=last_plot(), units="mm", width=100, height=20, dpi=1200)
}

## add a markup reference to this dataframe
stats$varianceChart <- sprintf('\\raisebox{-.4\\totalheight}{\\includegraphics[width=0.2\\textwidth, height=20mm]{%s/%s.png}}', graph_directory, stats$n) 

df.table <- stats[, c(1,2,5)]
colnames(df.table) <- c("Person Name", "Time taken", "Variance Chart")
```

```{r}
library(knitr)
kable(df.table[, c(1,2)], caption="Rows look neat and a sensible distance apart")
kable(df.table, caption="Rows are separated a long way apart and images and text are misaligned")
```

这篇关于使用markdown,rstudio和knitr对齐表格中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆