Compile RMarkdown PDF with Waffle Chart and Glyphs FAILURE. MWE included - rstudio

I am unable to compile PDF using RMarkdown, the waffle package, and glyphs
It doesn't matter if I use the TIKZ device or PDF rendering. The document compiles without a problem to HTML.
The only work around I can think of right now is to create SVG graphic with the HTML compiler, then to reference those files in my intermediate .TEX file.
Notice that if you simply run the code below the line that says, " ## ---- waffle_figure ---- ". It should create the chart given that you've previously installed the fontawesome font on your system, installed the extrafont package in R, and run the font_install() command.
---
title: "Waffle"
output:
pdf_document:
latex_engine: xelatex
html_document: default
header-includes:
- \usepackage{fontspec}
- \defaultfontfeatures{Extension = .otf}
- \usepackage{fontawesome}
- \usepackage{tikz}
---
```{r setup, include=FALSE}
library(knitr)
library(tikzDevice)
knitr::opts_chunk$set(warning = FALSE, error = FALSE, message = FALSE, results='hide', echo = FALSE, dev = "tikz", external = TRUE)
```
\faTwitter
## Waffle Plot
You can also embed plots, for example: \newline
```{r pressure, echo=FALSE, dev="tikz"}
## ---- waffle_figure ----
loadpackages <- function(package.list = c("ggplot2", "Rcpp")) {
new.packages <- package.list[!(package.list %in% installed.packages()[,"Package"])]
if (length(new.packages)){install.packages(new.packages, repos = 'http://cran.us.r-project.org')}
lapply(eval(package.list), require, character.only = TRUE)}
loadpackages(c("waffle", "extrafont", "grid", "gridExtra", "tikzDevice"))
parts <- c(40, 30, 20, 10)
waffle(parts,
rows=10,
use_glyph = "user",
glyph_size = 5)
```

The Waffle package is now updated! Now, both the quartz and cairo devices work with knitr/rmarkdown. Huge thank you's are due to Bob Rudis and Dave Gandy.
The revised code includes latin modern (LaTeX) font in order to demonstrate that it is possible to implement latex fonts alongside fontawesome glyphs in waffle charts.
In order for the code to work, you must first install lmroman10-regular-webfont.ttf and fontawesome-webfont.ttf from their respective websites: Click on the webfont kit link and Fontawesome download.
title: "Waffle"
output:
pdf_document:
latex_engine: xelatex
html_document: default
header-includes:
- \usepackage{fontspec}
- \defaultfontfeatures{Extension = .otf}
- \usepackage{fontawesome}
- \usepackage{tikz}
---
```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(warning = FALSE, error = FALSE, message = FALSE, results='hide', echo = FALSE, dev = "tikz", external = TRUE)
```
## Font Awesome Gyphy
Font awesome glyphs are easy to integrate into the main text. For example: \faTwitter.
## Waffle Plot
You can also embed plots with glyphs and custom fonts, for example: \newline
```{r pressure, echo=FALSE, dev="quartz_pdf", dev.args=list(family = "Helvetica")}
## ---- waffle_figure ----
loadpackages <- function(package.list = c("ggplot2", "Rcpp")) {
new.packages <- package.list[!(package.list %in% installed.packages()[,"Package"])]
if (length(new.packages)){install.packages(new.packages, repos = 'http://cran.us.r-project.org')}
lapply(eval(package.list), require, character.only = TRUE)}
loadpackages(c("waffle", "extrafont", "grid", "gridExtra"))
# font_import() # Run this command, type "y", and press enter after installing new fonts.
parts <- c(40, 30, 20, 10)
waffle(parts,
rows=10,
use_glyph = "user",
glyph_size = 7)+ggtitle("Some Sample Text Here")+
theme(plot.title = element_text(family="LM Roman 10"))
```

Related

Setting image width in table vs main text is not the same in RMarkdown

I have an image I'm putting in a table and the size is completely different for the HTML version compared to the PDF. I prefer the PDF version but don't know how to make the HTML get the same size as the image in the main text (the image in table is oto small).
---
title: "Untitled"
output:
pdf_document: default
html_document: default
date: "`r Sys.Date()`"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
| Icônes | Explications | Exemple |
|:-------------|:-----------------------|:--------------------------|
| ![](../../../images/icones_Rstudio/cancel_2x.png){width="5%"} | `R` est en exécution | NA |
main
![](../../../images/icones_Rstudio/cancel_2x.png){width="5%"}
The image I used is here. How to make the image size in the table the same without changing the width parameter? I output both HTML and PDF from the same RMarkdown and I don't want to have 2 different files to set the size of these images... so in the end, the images in the HTML should be like the one in the PDF.

refer to an editable datatable in flexdashboard r

I have a flexdashboard with editable cells in a datatable r_data.
The user can update the cells. I would then like to be able to refer to the updated datatable (updated_df) for further manipulation and save the final result as a file
Is this possible?
Here is MRE:
---
title: "Untitled"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(DT)
library(tidyverse)
library(shiny)
```
Column {data-width=500}
-----------------------------------------------------------------------
### Chart A
```{r}
data = head(iris)
r_data = renderDT(datatable(data,
editable = "cell"))
r_data
```
Column {data-width=500}
-----------------------------------------------------------------------
### Chart B
```{r}
updated_df = reactive({
new = r_data()[,1:4]*3
write.csv(new,"new.csv")
})
updated_df
```

Images Don't Display in Rshiny

images don't display correctly (empty image displays) in R shiny, both internal as external (app.R) runs
similar questions posted in the past on this site do not provide an adequate answer: the solution of running the application through app.R doesn't solve the problem for me, image still isn't displayed
in the code: image is added to the main panel , both tried from documents as from web (converting images to web link).
example image: https://ibb.co/Bt6v6W9
I tried both to include the image through documents (local working directory) as by converting the image to a web link.
how the output looks: https://cdn1.imggmi.com/uploads/2019/4/24/d65ae8a21decc6adb1d14db9a3e9bf75-full.png
Anyone an idea for solution? As mentioned, running the application through app.R doesn't work, output remains the same.
library(shiny)
library(png)
# See above for the definitions of ui and server
library(shiny)
library(png)
# Define UI for app that draws a histogram ----
ui <- fluidPage(
# App title ----
titlePanel("Hello Shiny!"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of bins ----
sliderInput(inputId = "bins",
label = "Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Histogram ----
plotOutput(outputId = "distPlot"),
img(src='DataVIS1.png', align = "right",height=168,width=70)
##output: png image
)
)
)
server <- function(input, output) {
# Histogram of the Old Faithful Geyser Data ----
# with requested number of bins
# This expression that generates a histogram is wrapped in a call
# to renderPlot to indicate that:
#
# 1. It is "reactive" and therefore should be automatically
# re-executed when inputs (input$bins) change
# 2. Its output type is a plot
output$distPlot <- renderPlot({
x <- faithful$waiting
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = "#75AADB", border = "white",
xlab = "Waiting time to next eruption (in mins)",
main = "Histogram of waiting times")
})
}
shinyApp(ui = ui, server = server
)
You should throw the code that creates the image in the server side, encapsulate it inside a a renderPlot({}) function that you've named, then plot the output just after the "distPlot" plotOutput. I couldn't get your img(src=...) code to work so I used a raster plot which is functionally the same for this purpose. A minified example is as follows:
library(shiny)
library(png)
ui <- fluidPage(
mainPanel(
plotOutput(outputId = "png")
)
)
server <- function(input, output) {
output$png <- renderPlot({
pic = readPNG('path/to/image.png')
plot.new()
grid::grid.raster(pic)
})
}
shinyApp(ui = ui, server = server)
Putting this into your code yields:
library(shiny)
library(png)
# See above for the definitions of ui and server
library(shiny)
library(png)
# Define UI for app that draws a histogram ----
ui <- fluidPage(
# App title ----
titlePanel("Hello Shiny!"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of bins ----
sliderInput(inputId = "bins",
label = "Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Histogram ----
plotOutput(outputId = "distPlot"),
###Changed code here
plotOutput(outputId = "png")
##output: png image
)
)
)
server <- function(input, output) {
# Histogram of the Old Faithful Geyser Data ----
# with requested number of bins
# This expression that generates a histogram is wrapped in a call
# to renderPlot to indicate that:
#
# 1. It is "reactive" and therefore should be automatically
# re-executed when inputs (input$bins) change
# 2. Its output type is a plot
output$distPlot <- renderPlot({
x <- faithful$waiting
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = "#75AADB", border = "white",
xlab = "Waiting time to next eruption (in mins)",
main = "Histogram of waiting times")
})
###New function
output$png <- renderPlot({
pic = readPNG('path/to/image.png')
plot.new()
grid::grid.raster(pic)
})
}
shinyApp(ui = ui, server = server
)
... And displays:

plot.CA() renders in shiny app locally but not when app is deployed

I have created a Shiny app that takes user input and creates a CA plot. It works just fine when I run the app locally, but for some reason when I deploy the dashboard, the image of the plot won't appear. I can see in the logs that the data uploading and reformatting into a proper data frame is working just fine, but the plot itself is failing to render.
Does anyone know why this might be? I posted my code below (you'll see some print() lines in my code that was used for debugging). Any help would be greatly appreciated!
#PERCEPTUAL MAPPING DASHBOARD
library(FactoMineR)
library(factoextra)
library(SensoMineR)
library(shinythemes)
library(ca)
ui <- fluidPage(theme = shinytheme("darkly"),
# Application title
titlePanel("Perceptual Map Dashboard"),
sidebarLayout(
# Sidebar with a slider and selection inputs
sidebarPanel(
#Excel doc row and column names
numericInput(inputId="startcol",label="Input start column of CSV file:",value="", min=1,max=10000),
numericInput(inputId="endcol",label="Input end column of CSV file:",value="", min=1,max=10000),
#Inputing brands and emotions
br(),
numericInput(inputId = "rownums",label = "How many emotions/characteristics are you evaluating?",value = "", min = 1,max = 10000),
br(),
h6("Note: Please enter brands and emotions/characteristics in the order that they appear in the excel document exported from Survey Gizmo."),
textInput ( 'brands', 'List the brands included in your perceptual map (separated by commas):', value=""),
textInput ( 'emotions', 'List the emotions/characteristics included in your perceptual map (separated by commas):', value=""),
#Removing brands and emotions
#Select graph type
textInput(inputId="plottitle",label="Title your graph:"),
#Upload Excel Grid
fileInput(inputId = 'data', 'Upload CSV File',
accept=c('.csv')),
actionButton("go","Create Map")
),
# Visual Output
mainPanel(
wellPanel(h4('Visual'),
h5("Once your visual appears, just right click it to save it as a .png file.")),
plotOutput(outputId = "plot", width = "100%", height=500)
# downloadButton("downloadPlot", "Download Visual")
)
)
)
server <- function(input,output){
K <- eventReactive(input$go,{
x <- read.csv(input$data$datapath, header = F)
x[!is.na(x)] <- 1
x[is.na(x)] <- 0
x<-x[,as.numeric(input$startcol):as.numeric(input$endcol)]
column.sums<-colSums(x)
print(column.sums)
pmd.matrix<-matrix(column.sums, byrow = T, nrow=as.numeric(input$rownums))
pmd.df2<-as.data.frame(pmd.matrix)
colnames(pmd.df2) = unlist(strsplit(as.character(input$brands),","))
print(pmd.df2)
row.names(pmd.df2)= unlist(strsplit(as.character(input$emotions),","))
print(pmd.df2)
pmd.df2[-nrow(pmd.df2),]
print(pmd.df2)
fit <- CA(pmd.df2, graph=F)
return(fit)
})
p <- eventReactive(input$go,{
input$plottitle
})
output$plot<- renderPlot({
plot.CA(K(), col.row = "blue", col.col="black", cex=1, new.plot=T,
title=p())
})
}
shinyApp(ui = ui, server = server)
What I suggest to you is to check whether this issue is specific to your plot or if plot.CA is not working with shiny in general. Try to "deploy" (apparently, you don't use a webserver?) the following app
library(FactoMineR)
library(shiny)
data(children)
res.ca <- CA(children, col.sup = 6:8, row.sup = 15:18)
shinyApp(
fluidPage(plotOutput("plot")),
function(input, output, sesison) {
output$plot <- renderPlot({
plot.CA(res.ca)
})
}
)
If this does work, there might be something wrong with your model or maybe there are name collusions between the ca package and the FactorMineR package.
If this does not work, try the following instead
## use same data/libraries as above
myfile <- tempfile(fileext = ".png")
shinyApp(
fluidPage(imageOutput("plot")),
function(input, output, sesison) {
output$plot <- renderImage({
png(file = myfile)
plot.CA(res.ca)
dev.off()
list(src = myfile)
}, deleteFile = FALSE)
}
)
And see
Whether the app works now
Whether myfile gets created and contains reasonable contents.

Set font and font size in R Console programmatically?

Is it possible to set the console font and font size, as I would with "Edit->GUI preferences", programmatically? How would a function for this look like? I am on windows.
On Windows (at least), the $R_HOME/etc/Rconsole config file sets many optional parameters for the console and pager. Here's the section that you could hand-edit to change the default font and font size:
## Font.
# Please use only fixed width font.
# If font=FixedFont the system fixed font is used; in this case
# points and style are ignored. If font begins with "TT ", only
# True Type fonts are searched for.
font = TT Courier New
points = 10
style = normal # Style can be normal, bold, italic
To change the values from the command line of an active R session, you could use the loadRconsole() function. It reads in a text file containing directives of the form shown above, which will overwrite the values read from Rconsole when R was launched. Here's an example:
temp <- tempfile()
cat("points = 13\n", file = temp)
cat("style = italic\n", file = temp, append = TRUE)
loadRconsole(file = temp)
## And then, to reset to the defaults:
loadRconsole(file = file.path(R.home(), "etc/Rconsole"))

Resources