[英]Create dynamic ggvis chart from uploaded file in shiny
我想用Shiny和ggvis來:
1)上傳數據集
2)讓用戶選擇2列(x,y)
3)從上傳的數據集中返回顯示(x,y)的ggvis圖
我已經嘗試過編輯Shiny Interactivity頁面中的示例以及電影資源管理器示例。 但是,不顯示任何圖表。
我認為我的問題是上傳數據集,但我不知道從哪里開始...有什么建議嗎?
注意 - 我也嘗試使用rCharts,但我遇到了類似的問題,沒有顯示圖表。
server.R
library(shiny)
library(dplyr)
library(ggvis)
shinyServer(function(input, output, session) {
fileHeaderNames <- reactive({
infile <- input$datfile
if(is.null(infile))
return(NULL)
d <- read.csv(infile$datapath, header = T)
return(names(d))
})
# dynamic variable names
observe({
updateSelectInput(session, 'x', choices = fileHeaderNames())
updateSelectInput(session, 'y', choices = fileHeaderNames())
}) # end observe
# uploading data set
theData <- reactive({
validate(
need(input$datfile != "", "Please upload a file")
)
infile <- input$datfile
dat <- read.csv(infile$datapath,
header = T,
stringsAsFactors = F)
if(is.null(infile)) return(NULL)
data.frame(x = dat[, input$x],
y = dat[, input$y])
})
# A simple visualisation. In shiny apps, need to register observers
# and tell shiny where to put the controls
theData %>%
ggvis(~x, ~y) %>%
layer_points() %>%
bind_shiny("plot", "plot_ui")
})
ui.R
library(ggvis)
library(shiny)
shinyUI(pageWithSidebar(
div(),
sidebarPanel(
fileInput('datfile', ''),
selectInput('x', 'x:' ,'x'),
selectInput('y', 'y:', 'y'),
uiOutput("plot_ui")
),
mainPanel(
ggvisOutput("plot")
)
))
這是一次嘗試,我添加了幾個反應塊來獲取應該在繪圖軸上添加的名稱。
您可以使用的技巧是創建一個具有兩列x
和y
的過濾數據框,並在用戶更改selectInput
的值時更改。 然后,您可以告訴ggvis
從該過濾的數據ggvis
繪制x
和y
,並且該圖將是交互式的。
library(shiny)
library(dplyr)
library(ggvis)
shinyServer(function(input, output, session) {
#load the data when the user inputs a file
theData <- reactive({
infile <- input$datfile
if(is.null(infile))
return(NULL)
d <- read.csv(infile$datapath, header = T)
d
})
# dynamic variable names
observe({
data<-theData()
updateSelectInput(session, 'x', choices = names(data))
updateSelectInput(session, 'y', choices = names(data))
}) # end observe
#gets the y variable name, will be used to change the plot legends
yVarName<-reactive({
input$y
})
#gets the x variable name, will be used to change the plot legends
xVarName<-reactive({
input$x
})
#make the filteredData frame
filteredData<-reactive({
data<-isolate(theData())
#if there is no input, make a dummy dataframe
if(input$x=="x" && input$y=="y"){
if(is.null(data)){
data<-data.frame(x=0,y=0)
}
}else{
data<-data[,c(input$x,input$y)]
names(data)<-c("x","y")
}
data
})
#plot the ggvis plot in a reactive block so that it changes with filteredData
vis<-reactive({
plotData<-filteredData()
plotData %>%
ggvis(~x, ~y) %>%
layer_points() %>%
add_axis("y", title = yVarName()) %>%
add_axis("x", title = xVarName()) %>%
add_tooltip(function(df) format(sqrt(df$x),digits=2))
})
vis%>%bind_shiny("plot", "plot_ui")
})
編輯:添加工具提示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.