How to store r ggplot graph as html code snippet
I ended up generating a temparory image file, then base64 encoding it, within a function I called encodeGraphic()
(borrowing code from LukeA's post):
library(ggplot2)
library(RCurl)
library(htmltools)
encodeGraphic <- function(g) {
png(tf1 <- tempfile(fileext = ".png")) # Get an unused filename in the session's temporary directory, and open that file for .png structured output.
print(g) # Output a graphic to the file
dev.off() # Close the file.
txt <- RCurl::base64Encode(readBin(tf1, "raw", file.info(tf1)[1, "size"]), "txt") # Convert the graphic image to a base 64 encoded string.
myImage <- htmltools::HTML(sprintf('<img src="data:image/png;base64,%s">', txt)) # Save the image as a markdown-friendly html object.
return(myImage)
}
HTMLOut <- "~/TEST.html" # Say where to save the html file.
g <- ggplot(mtcars, aes(x=gear,y=mpg,group=factor(am),color=factor(am))) + geom_line() # Create some ggplot graph object
hg <- encodeGraphic(g) # run the function that base64 encodes the graph
forHTML <- list(h1("My header"), p("Lead-in text about the graph"), hg)
save_html(forHTML, HTMLOut) # output it to the html file.
R chart convert to html format without other files
Just add selfcontained = TRUE
to your last line:
htmlwidgets::saveWidget(as_widget(plotly), selfcontained = TRUE, file = "xxxx/graph.html")
How to plot ggplotly and class c('chorddiag', 'htmlwidget') plots together
You can glue the "plots" together using htmltools::browsable
. Try this:
library(htmltools)
browsable(
tagList(list(
tags$div(
#style = 'width:80%;display:block;float:left;',
plt_interactive
),
tags$div(
#style = 'width:20%;display:block;float:left;',
chord
)
))
)
An alternative approach would be to use crosstalk::bscols(plt_interactive, chord)
.
Using for loops to generate html content
Move the loop outside of tags$div
.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!--begin.rcode, echo=FALSE, message=FALSE, warning=FALSE
library(htmltools)
paragraphs = c("Paragraph1","Paragraph2","Paragraph3")
p <- list()
for(i in paragraphs){
p <- c(p, list(tags$p(i)))
}
tags$div(p)
end.rcode-->
</body>
</html>
This can also be written with purr::map
.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!--begin.rcode, echo=FALSE, message=FALSE, warning=FALSE
library(htmltools)
paragraphs = c("Paragraph1","Paragraph2","Paragraph3")
tags$div(purrr::map(paragraphs, tags$p))
end.rcode-->
</body>
</html>
Generate html code using lapply() with multiple arguments
You can use apply
row-wise, and specify class, id, and content from your data frame as follows.
library(htmltools)
tags$div(apply(df, 1, function(x) {
tags$p(class = x[["class"]], id = x[["id"]], x[["paragraph"]])
}))
Output
<div>
<p class="alert" id="id_1">paragraph1</p>
<p class="good" id="id_2">paragraph2</p>
<p class="alert" id="id_3">paragraph3</p>
</div>
Alternate text and ggplot output in vectorized function in Rmarkdown output
You can do it using a function from this answer: https://stackoverflow.com/a/50352019/2554330. The issue is that knitr
won't output the right Markdown source to do what you want, so you need to do what it should be doing. So define this function:
encodeGraphic <- function(g) {
png(tf1 <- tempfile(fileext = ".png")) # Get an unused filename in the session's temporary directory, and open that file for .png structured output.
print(g) # Output a graphic to the file
dev.off() # Close the file.
txt <- RCurl::base64Encode(readBin(tf1, "raw", file.info(tf1)[1, "size"]), "txt") # Convert the graphic image to a base 64 encoded string.
myImage <- htmltools::HTML(sprintf('<img src="data:image/png;base64,%s">', txt)) # Save the image as a markdown-friendly html object.
return(myImage)
}
Then you can get the output that you want using this code. I needed to insert a few extra newlines, but otherwise it's basically just what you had, run through encodeGraphic
:
```{r plot, results='asis'}
dataset %>% iwalk(
~{
paste0("\n## ", .y, "\n") %>% cat()
dataset %$% qplot(.x, xlab = .y, geom = "bar") %>%
encodeGraphic() %>% cat()
}
)
```
have a list of ggplots in R, would like to put them in a folder
You can do a simple loop:
for(i in seq_along(p.list)){
jpeg(filename = paste0("ggplot_", sort(unique(new$tree))[i], ".jpg"))
print(p.list[[i]])
dev.off()
}
This will write the files ggplot_1.jpg
, ggplot_2.jpg
etc to your home directory.
ggplot plots in scripts do not display in Rstudio
I recently happened on this question and realized that the most up to date way is to call show(p)
after creating the plot.
Related Topics
How to Retrieve the Most Repeated Value in a Column Present in a Data Frame
Ggplot2: How to Adjust Fill Colour in a Boxplot (And Change Legend Text)
Dplyr Filter() with SQL-Like %Wildcard%
Importing Wikipedia Tables in R
Unquote the Variable Name on the Right Side of Mutate Function in Dplyr
Multiple Colors in a Facet Strip Background
Reshaping Several Variables Wide with Cast
Ggplot2 Bar Plot with Two Categorical Variables
Check If Value Is in Data Frame
How to Loop Through a Folder of CSV Files in R
Taking a Disproportionate Sample from a Dataset in R
How to Do Gaussian Elimination in R (Do Not Use "Solve")
Evaluate Inline R Code in Rmarkdown Figure Caption
Ggplot2 Multiline Title, Different Indentations
Creating a Monthly/Yearly Calendar Image with Ggplot2
Beginner Tips on Using Plyr to Calculate Year-Over-Year Change Across Groups