首页 文章

R Shiny服务器无法呈现正确的ggplot字体系列

提问于
浏览
3

我正在尝试将一个漂亮的字体应用于在Shiny应用程序中呈现的ggplot .

使用family =“[fontname]”在RStudio中设置所需的字体(在同一服务器上)可以正常工作 . 这里要求使用“serif”字体系列:

Image of correct ggplot font family rendering in rstudio

但是,当ggplot嵌入到Shiny renderPlot({})函数中时,字体系列不会更改默认值 . 这里要求使用相同的“serif”字体系列:

Image of incorrect ggplot font family rendering in Shiny app

字体大小和字体(粗体,斜体)的更改按预期工作 . 我已经在RStudio和闪亮的应用程序中使用fonts()和pdfFonts()检查了已安装的字体名称,然后尝试了列出的以及“serif”,“sans”和“mono”,但都无济于事 . 我也尝试过loadfonts() .

一个最小的例子:

server.R

require(ggplot2)
require(ggthemes)
require(extrafont)

shinyServer(function(input, output) {
  df <- data.frame(a=rnorm(100), b=rnorm(100))

  output$the_plot <- renderPlot({
    p <- ggplot(df, aes(x=a, y=b), environment=environment()) + 
      xlab("Alpha") + 
      ylab("Beta") +
      geom_point() +
      theme(text=element_text(family="serif", size=16))

    print(p)
  })
})

ui.R

library(shiny)

shinyUI(fluidPage(
  sidebarLayout(
    sidebarPanel(
      h6("Font test")
    ),

    mainPanel(
      plotOutput("the_plot")
    )
  )
))

Edit:a similar unanswered question但是寻求pdf而不是png输出 . 现在也尝试过R基本图形而不是ggplot,结果相同 .

1 回答

  • 3

    作为一种解决方法,我使用renderImage()重新创建了大部分renderPlot()功能,如this Shiny tutorial article中所述 . 令人高兴的是,这使得反锯齿字体更加丰富 . 希望这对其他人有用 .

    ui.R修改为

    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
    
    })
    

相关问题