R ggplot图表不会刷新

时间:2018-02-19 06:05:06

标签: r shiny

我有.csv文件,如下所示:

 "name","task","progress","category","status"
 "Mike","call","60","HR","100% completed"
 "Josh","meeting","60","Management","100% completed"
 "Anna","interview","30","Marketing","on hold"

我有一个提交按钮,每次按下时都会在.csv文件中添加一行,但只有刷新页面时图形才会更新。

shinyServer(function(input, output) {

    saveData <- function(data) {
data <- as.data.frame(t(data))

if (exists("responses")) {
  responses <<- rbind(responses, data)
} else {
  responses <<- data}

write.csv(responses, file = "read.csv", row.names = FALSE)}

  observeEvent(input$submit, {
saveData(formData()) })



output$plot<-renderPlot({
data<-read.csv("C:/Users/Desktop/project/read.csv")
ggplot(data, aes(x=name, y=as.numeric(progress), group=task, fill= task, color= task)) +
geom_bar( stat="identity", position = "dodge")+theme_minimal()+
geom_text(aes(label=sprintf("%1.2f%%",progress)), color="black", position=position_dodge(width=1), vjust=2)+
ylim(c(0, 100))

  })
}

问题是什么?

1 个答案:

答案 0 :(得分:0)

您需要在renderPlot()函数中添加一个反应元素。

    shinyServer(function(input, output) {
        rv <- reactiveValues(update = 0)
        saveData <- function(data) {
            data <- as.data.frame(t(data))

            if (exists("responses")) {
                responses <<- rbind(responses, data)
            } else {
                responses <<- data
            }

            write.csv(responses, file = "read.csv", row.names = FALSE)
        }

        observeEvent(input$submit, {
            saveData(formData())
            rv$update <- rv$update + 1 
        })

        output$plot<-renderPlot({
            rv$update
            data <- read.csv("C:/Users/Desktop/project/read.csv")
            ggplot(data, aes(x=name, y=as.numeric(progress), group=task, fill= task, color= task)) +
            geom_bar( stat="identity", position = "dodge")+theme_minimal()+
            geom_text(aes(label=sprintf("%1.2f%%",progress)), color="black", position=position_dodge(width=1), vjust=2)+
ylim(c(0, 100))

  })
}

每次renderPlot()元素更新时,都会导致rv$update触发。您也可以通过在input$submit中包含renderPlot()来引发此行为,但由于您正在写入文件并从文件中读取,因此最好强制按顺序触发函数。