我创建了以下数据框和闪亮的应用程序
# Import packages
library(readxl)
require(ggplot2)
require(janitor)
require(lubridate)
require(shiny)
require(plotly)
require(reshape2)
#generate date randomly
rdate <- function(x,
min = paste0(format(Sys.Date(), '%Y'), '-01-01'),
max = paste0(format(Sys.Date(), '%Y'), '-12-31'),
sort = TRUE) {
dates <- sample(seq(as.Date(min), as.Date(max), by = "day"), x, replace
= TRUE)
if (sort == TRUE) {
sort(dates)
} else {
dates
}
}
接下来,我们创建一个数据框
DF<-as.data.frame("Date"<-rdate(100))
DF$variable<-LETTERS[seq( from = 1, to = 10 )]
DF$Value<-round(runif(1:nrow(DF),min = 10, max = 50))
# subset the dataframe
DF<-DF[,c(2:4)]
DF
# Write to csv
write.csv(DF, file = "Book1.csv", col.names = F)
接下来,我们创建闪亮的APP
# UI creation
UI<-fluidPage(fileInput("file", "Browse",
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
#selectInput(inputId = "Speciesname", label = "Name",choices =
#NULL,selected = NULL),
plotOutput(outputId = "plot1" ))
# Server creation
Server<-function(input, output, session){
output$plot1<-renderPlot({
infile <- input$file
if (is.null(infile)) {
# User has not uploaded a file yet
return(NULL)
}
Book1 <- read.csv(input$file$datapath, stringsAsFactors = F)
Book1<-data.frame(Book1)
Book2<-remove_empty_rows(Book1)
ggplot(DF, aes(x = Date, y = Value, colour = variable)) +
geom_line() +
ylab(label="Number of Sales") +
xlab("Sales Week")
}
)
}
shinyApp(UI, Server)
在此应用中,该图形在名为Shiny UI的输出中生成。
当我在服务器中进行以下更改时,该图不是在闪亮的UI中生成的,而是在r studio控制台中生成的
Book2<-remove_empty_rows(Book1)
P<- ggplot(DF, aes(x = Date, y = Value, colour = variable)) +
geom_line() +
ylab(label="Number of Sales") +
xlab("Sales Week")
return(ggplotly(p))
我无法在闪亮的UI控制台中获得该图。我要求某人帮助我。我找不到错误
答案 0 :(得分:2)
如果您在闪亮的应用程序中使用Plotly,则plotOutput()
和renderPlot()
将不起作用。您需要拥有plotlyOutput()
和renderPlotly()
。下面的代码应该工作。我取出了fileInput和read.csv使其变得更容易。
library(shiny)
library(plotly)
rdate <- function(x,
min = paste0(format(Sys.Date(), '%Y'), '-01-01'),
max = paste0(format(Sys.Date(), '%Y'), '-12-31'),
sort = TRUE) {
dates <- sample(seq(as.Date(min), as.Date(max), by = "day"), x, replace
= TRUE)
if (sort == TRUE) {
sort(dates)
} else {
dates
}
}
UI<-fluidPage(
plotlyOutput(outputId = "plot1" ))
# Define server logic required to draw a histogram
server <- function(input, output) {
output$plot1 <- renderPlotly({
# generate bins based on input$bins from ui.R
DF<-data.frame(Date = rdate(100))
DF$variable<-LETTERS[seq( from = 1, to = 10 )]
DF$Value<-round(runif(1:nrow(DF),min = 10, max = 50))
g <- ggplot(DF, aes(x = Date, y = Value, colour = variable)) +
geom_line() +
ylab(label="Number of Sales") +
xlab("Sales Week")
ggplotly(g)
})
}
# Run the application
shinyApp(ui = UI, server = server)