gat*_*rer 6 r ggplot2 shiny shiny-server
我正在尝试将漂亮的字体应用于在Shiny应用程序中呈现的ggplot。
使用family =“ [fontname]”在RStudio中(在同一服务器上)设置所需的字体可以正常工作。这里要求一个“ serif”字体家族:
但是,将ggplot嵌入Shiny renderPlot({})函数后,字体系列不会更改为默认值。这里要求使用相同的“ serif”字体家族:
字体大小和字体(粗体,斜体)的更改按预期工作。我已经在RStudio和闪亮的应用程序中使用fonts()和pdfFonts()检查了已安装的字体名称,然后尝试列出的字体名称以及“ serif”,“ sans”和“ mono”,但均无济于事。我也尝试过loadfonts()。
一个最小的例子:
服务器
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)
})
})
Run Code Online (Sandbox Code Playgroud)
用户界面
library(shiny)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
h6("Font test")
),
mainPanel(
plotOutput("the_plot")
)
)
))
Run Code Online (Sandbox Code Playgroud)
编辑:有一个类似的未解决的问题,但寻求pdf而不是png输出。现在也尝试使用R基本图形而不是ggplot,结果相同。
作为一种解决方法,如本Shiny教程文章所述,我使用renderImage()重新创建了很多renderPlot()功能。。令人高兴的是,这使抗锯齿字体显得格外丰富。希望这对其他人有用。
ui.R修改为
mainPanel(
imageOutput("myImage")
)
Run Code Online (Sandbox Code Playgroud)
服务器
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
})
Run Code Online (Sandbox Code Playgroud)