ちょっとしたアプリケーションを作って、自分以外の、Rが使えない人でもデータを入力したら出力を得られるような仕様にしたい。
そこで、R のshiny を使ってweb にアクセスしたら使えるようにするわけだが、ローカル環境で構築したshiny アプリではプロット上の日本語フォントがきちんと表示されるのに、shinyapps.io にアップロードしてserver 環境下で使うと、日本語フォントが表示されない。
これはshiny server がlinux ベースで、日本語フォントを標準装備していないかららしいが、library(showtext)
とすると日本語フォントが対応するらしい。
shinyapps.io - RjpWiki
しなかった。
下記を参考に、shiny server にR からコマンドを実行してフォントを読み込ませる。
リンクではsh
ファイルをbash
で実行しているが、system
関数でR側からコマンドを実行しているので、全部R側のスクリプトに納めておいた。
shinyapps.ioで任意の日本語フォントを使う - mana.bi
library(shiny)
bashcode <- "
mkdir ~/tmp;
cd ~/tmp;
curl -O -L https://moji.or.jp/wp-content/ipafont/IPAexfont/IPAexfont00401.zip;
unzip IPAexfont00401.zip;
mkdir -p ~/.fonts/ipa;
cp ./IPAexfont00401/*.ttf ~/.fonts/ipa;
fc-cache -f ~/.fonts;
"
system(bashcode)
ui <- fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File",
multiple = FALSE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
tags$hr(),
checkboxInput("header", "Header", TRUE),
radioButtons("sep", "Separator",
choices = c(Comma = ",",
Semicolon = ";",
Tab = "\t"),
selected = ","),
radioButtons("quote", "Quote",
choices = c(None = "",
"Double Quote" = '"',
"Single Quote" = "'"),
selected = '"'),
tags$hr(),
radioButtons("disp", "Display",
choices = c(Head = "head",
All = "all"),
selected = "head")
),
mainPanel(
tableOutput("contents"),
plotOutput("plot"),
)
)
)
server <- function(input, output) {
hoge <- iris
dat <- reactive({
if(is.null(input$file1$datapath)){
return(NULL)
} else {
req(input$file1)
huga <- read.csv(input$file1$datapath)
return(huga)
}
})
output$contents <- renderTable({
req(input$file1)
tryCatch(
{
df <- read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
},
error = function(e) {
stop(safeError(e))
}
)
if(input$disp == "head") {
return(head(df, input$is_holiday))
}
else {
return(df)
}
})
output$plot <- renderPlot({
plot(1, type="n")
title("日本語")
text(1, 1, "ほげほげ")
})
}
shinyApp(ui, server)