01_helloは、入力用スライダーと出力用のプロットがあり、server.Rで入力された値をプロットに変換するプログラムとなっています。
「01_hello」の実行
library(shiny) runExample("01_hello")
server.R
library(shiny) # ヒストグラムを描くためのサーバ側を定義 function(input, output) { # ヒストグラムを描く式は、以下に示すrenderPlot関数の呼び出しの中で定義 # # 1) renderPlot関数はreactive、すなわち入力が変化したときに自動的に再計算される # 2) 出力型はプロット output$distPlot <- renderPlot({ x <- faithful[, 2] # オルド・フェイスフル・ガイザーデータ bins <- seq(min(x), max(x), length.out = input$bins + 1) # 特定のbinごとにヒストグラムを描画 hist(x, breaks = bins, col = 'darkgray', border = 'white') }) }
Code license:MIT
function(input, output)
の宣言により、入力はinput$
で、表示する出力はoutput$
で表記する。01_helloではinput$bins
とoutput$distPlot
が対応しており、それぞれui.Rに同名の変数があるoutput$distPlot
には、renderPlot()
が返すプロットが入る。renderPlot()
はreactiveなので、ui.RでdistPlotは入力が変わるたびに再計算されて表示される。faithful
は、イエローストーン国立公園のオルド・フェイスフル・ガイザーという有名な間欠泉の噴火と待ち時間のデータセット。(input$ではない)
bins
に代入されているseq()
の返す値は、待ち時間の最小値min(x)と最大値max(x)を含むbinsで指定された数のリストhistでbinsで指定された値に対応する噴火時間xの値をヒストグラム化
ui.R
library(shiny) # ヒストグラムを描くためのUI側を定義 fluidPage( # タイトル titlePanel("Hello Shiny!"), # 入力用スライダーのあるサイドバーレイアウト sidebarLayout( sidebarPanel( sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30) ), # 生成された分布のプロットを表示 mainPanel( plotOutput("distPlot") ) ) )
Code license:MIT
fluidPage()
でuiオブジェクトを生成titlePanel()
でウィンドウのタイトルを定義sidebarLayout()
で、sidebarPanelとmainPanelの2つのパネルをサイドとメインに分けてレイアウト。sliderInput()
でサイドのスライドバーのタイトルや大きさを定義。mainPanelでは、(server.Rで動的に値が変化する) distPlotを引数として、
plotOutput()
でプロットを表示