Ggplot with Customized Font Not Showing Properly on Shinyapps.Io

ggplot with customized font not showing properly on shinyapps.io

I found a solution that seems to work on shinyapps.io (but not locally, since it is a Linux only solution. And somehow it did not work with my original 'ComicSans MS' font, but that font is not beautiful anyway.. ;-))

Here we go:

  1. Place custom font in www directory: e.g. IndieFlower.ttf from here
  2. Follow the steps from here

This leads to the following app.R file:

ibrary(ggplot2)
library(shiny)

dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')

ui <- fluidPage(plotOutput("plot"))

server <- function(input, output) {
output$plot <- renderPlot({
ggplot(mapping=aes(x=seq(1,10,.1), y=seq(1,10,.1))) +
geom_line(position="jitter", color="red", size=2) + theme_bw() +
theme(text=element_text(size = 16, family = "IndieFlower"))
})
}

shinyApp(ui = ui, server = server)

The plot looks like:

Sample Image

R Shiny server not rendering correct ggplot font family

As a workaround, I recreated much of the renderPlot() functionality using renderImage(), as described in this Shiny tutorial article. Happily this renders antialiased fonts galore. Hope this is of use to someone else.

ui.R amended to

    mainPanel(
imageOutput("myImage")
)

server.R

shinyServer(function(input, output, session) {

# A dynamically-sized plot
output$myImage <- renderImage({
# Read myImage's width and height. These are reactive values, so this
# expression will re-run whenever they change.
width <- session$clientData$output_myImage_width
height <- session$clientData$output_myImage_height

# For high-res displays, this will be greater than 1
pixelratio <- session$clientData$pixelratio

# A temp file to save the output.
outfile <- tempfile(fileext='.png')

# Generate the image file
png(outfile, width=width*pixelratio, height=height*pixelratio,
res=72*pixelratio)
plot(rnorm(100), rnorm(100), family="serif")
dev.off()

# Return a list containing the filename
list(src = outfile,
width = width,
height = height,
alt = "This is alternate text")
}, deleteFile = TRUE) # delete the temp file when finished

})

I try to change font in ggplot but get the error Extracting .afm files from .ttf files..., why?

The extrafontdb seems to contain only extracted .afm files from the previous font_import().

To load the fonts from the extrafontdb database you probably need to run:

extrafont::loadfonts()

See details in documentation.

But for proper font import you still need to have a .ttf file, see documentation:

.afm file contains the font metrics, which are the rectangular dimensions of each character that are needed for placement of the characters. These are not the glyphs, which the curves defining the visual shape of each character. The glyphs are only in the .ttf file.



Related Topics



Leave a reply



Submit