【发布时间】:2022-01-07 14:02:49
【问题描述】:
我在 Rbookdown 工作,我想在一个图中放置一个绘图和一个表格,我该如何实现?下面是我到目前为止使用的代码。你能帮忙吗?
```{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)
【问题讨论】:
-
我有个主意。但是这个基本情节对我来说是个问题。你能用ggplot2重现它吗?或者我可以用一个随机的情节来写我的答案给你一个冲动?
-
我目前正在尝试避免使用 ggplot 并尝试使用 Base R,但也许任何情节都可以!请写下你的答案!谢谢
-
看,我添加一个例子。我也可以问你,你为什么在这个时候尽量避免使用ggplot?
-
Manro,它不起作用,我想这是我的设置或其他什么,我为我的项目尝试了你的示例(将
kbl()更改为kable())。不过感谢您的努力。我正在避免使用 ggplot,因为我正在编写教育教科书,并且想要看起来简单的情节,没有花哨的东西,你认为 ggplot 在我将其剥离到基本情节时看起来会更好吗? -
当有人对应用外部库有任何限制时(+ 也许当您的系统资源不足时?),我看到使用 base
plot是“合理的”。在其他情况下 -ggplot更好。你也可以用 ggplot 制作简单的情节,为什么不呢。一会儿,我可以为您提供另一种解决方案。
标签: html r r-markdown figure kable