簡體   English   中英

Plot and table in one figure in R markdown for HTML output

[英]Plot and table in one figure in R markdown for HTML output

我在 Rbookdown 工作,我想在一個圖中放置一個 plot 和一個表格,我該如何實現? 下面是我到目前為止使用的代碼。 你能幫我嗎?


```{r echo=FALSE, message=FALSE, warning=FALSE, fig.height = 3.5, out.width = '70%', fig.align = "center"}

library(knitr)
library(kableExtra)
library(tidyverse)
library(latex2exp)

options(scipen=999)
mu = 0
sigma = 1
x = 1

# draw normal distribution
range = seq(mu - 4*sigma, mu + 4*sigma, 0.01)
y = dnorm(range, mu, sigma)

plot(range, y, 
     main = "Standard Normal Distribution", xlab = "Z-score", ylab = " ",
     type = 'l', ylim = c(0, max(y) + 0.01), axes = FALSE)
axis(1, at = seq(mu - 4*sigma, mu + 4*sigma, sigma))

# Add area to the left of x
cord.a = c(0, seq(min(range), x, 0.01))
cord.b = c(dnorm(seq(min(range), x, 0.01), mu, sigma), 0)
polygon(cord.a, cord.b, col = "#61a5ff")
text(x = 1.1, y = -.06, TeX('$z = 1.00$'), cex = .8, xpd=NA)
text(x = 0, y = .15, TeX('$p = .8413$'), cex = .8, xpd=NA)



# Create standard normal table
options(digits = 4)
u=seq(0,3.09,by=0.01)
p=pnorm(u)
m=matrix(p,ncol=10,byrow=TRUE)
df.m = as.data.frame(m)
z.values = c("**0.0**", "**0.1**", "**0.2**", "**0.3**", "**0.4**", "**0.5**", "**0.6**", 
             "**0.7**", "**0.8**", "**0.9**", "**1.0**", "**1.1**", "**1.2**", "**1.3**", 
             "**1.4**", "**1.5**", "**1.6**", "**1.7**", "**1.8**", "**1.9**","**2.0**", 
             "**2.1**", "**2.2**", "**2.3**", "**2.4**", "**2.5**", "**2.6**", "**2.7**", 
             "**2.8**", "**2.9**", "**3.0**")
df.z.values = as.data.frame(z.values)
new.m = df.z.values %>% 
  bind_cols(df.m)
kable(new.m,
      booktabs = TRUE,
      col.names =  c("$Z$", "0.00","0.01", "0.02", "0.03", "0.04", 
                     "0.05", "0.06", "0.07", "0.08", "0.09"), 
      escape = FALSE,
      caption = "Standaard Normaalverdeling",
      linesep = "",
      align = c('r')) %>% 
  kable_styling(font_size = 10)

試試這個解決方案:

```{r echo=FALSE, message=FALSE, warning=FALSE, include = FALSE}

library(kableExtra)

#make and save our table into working directory
table1 <- head(mtcars[1:5]) %>%
            kbl() %>%
            kable_styling(full_width = F) %>%
            save_kable("tab_kbl.png")

#make and save our plot into working directory
png('norm_pl.png')
plot(rnorm(10))
dev.off()
```


```{r,echo=FALSE, message=FALSE, warning=FALSE, fig.cap="My image", fig.align = "center"}

library(cowplot)

#combine our images in the one
img1 <- ggdraw() + draw_image("norm_pl.png", scale = 1)
img2 <- ggdraw() + draw_image("tab_kbl.png", scale = 1)
plot_grid(img1, img2)
```

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM