簡體   English   中英

如何在 Jupyter (R) 中渲染 LaTeX / HTML?

[英]How to render LaTeX / HTML in Jupyter (R)?

我剛開始在 R 中使用 Jupyter,我想知道是否有一種顯示 HTML 或 LaTeX 輸出的好方法。

這是我希望工作的一些示例代碼:

library(xtable)
x <- runif(500, 1, 50)
y <- x + runif(500, -5, 5)
model <- lm(y~x)
print(xtable(model), type = 'html')

它不呈現 HTML,而是將其顯示為純文本。 有什么辦法可以改變這種行為嗎?

repr (用於設置選項)和IRdisplay適用於 HTML。 其他人可能知道乳膠。

# Cell 1 ------------------------------------------------------------------

library(xtable)
library(IRdisplay)
library(repr)

data(tli)
tli.table <- xtable(tli[1:20, ])
digits(tli.table) <- matrix( 0:4, nrow = 20, ncol = ncol(tli)+1 )

options(repr.vector.quote=FALSE)

display_html(paste(capture.output(print(head(tli.table), type = 'html')), collapse="", sep=""))


# Cell 2 ------------------------------------------------------------------

display_html("<span style='color:red; float:right'>hello</span>")

# Cell 3 ------------------------------------------------------------------

display_markdown("[this](http://google.com)")

# Cell 4 ------------------------------------------------------------------

display_png(file="shovel-512.png")

# Cell 5 ------------------------------------------------------------------

display_html("<table style='width:20%;border:1px solid blue'><tr><td style='text-align:right'>cell 1</td></tr></table>")

在此處輸入圖片說明

對於最初的簡單用例,我找到了一個更簡單的答案。

如果您調用 xtable 而不將其包裝在打印調用中,那么它完全可以工作。 例如,

library(xtable)
data(cars)
model <- lm(speed ~ ., data = cars)
xtable(model)

在 Jupyter 中,您可以使用 Markdown。 只需確保將 Jupyter 單元格從代碼單元格更改為 Markdown 單元格。 完成此操作后,您只需在您擁有的 LaTex 前后放置一個雙美元符號(“$$”)。 然后運行單元格。

步驟如下: 1. 創建一個 Markdown 單元格。 2. $$ 一些 LaTex $$ 3. 在 Jupyter 中按下播放按鈕。

在會話中定義如下函數,會將 xtable 返回的對象顯示為 xtable 生成的 html:

repr_html.xtable <- function(obj, ...){
    paste(capture.output(print(obj, type = 'html')), collapse="", sep="")
}

library(xtable)
data(cars)
model <- lm(speed ~ ., data = cars)
xtable(model)

如果沒有repr_html.xtable函數,因為返回的對象也是data.frame類,內核中的顯示系統會通過repr::repr_html.data.frame豐富顯示該對象(=html table)。

只是不要print(...)對象:-)

將 html/Latex 表渲染/嵌入到 IR 內核 jupyter

R 中的一些包以 html 格式提供表格,如“knitr”,所以如果你想把這些表格放在筆記本中:

library(knitr)
library(kableExtra)
library(IRdisplay) #the package that you need

#we create the table
dt <- mtcars[1:5, 1:6]
options(knitr.table.format = "html") 
html_table= kable(dt) %>%
kable_styling("striped") %>%
add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2, "Group 3" = 2))

#We put the table in our notebook
display_html(toString(html_table))

或者例如,如果您有一個文件

display_latex(file = "your file path")

暫無
暫無

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

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