我创建了一个闪亮的应用程序,它有一个下拉列表来选择项目。当前代码如下所示:
#Import libraries
library(shiny)
library(plotly)
library(tidyr)
# Define UI
ui <- bootstrapPage(
selectInput(inputId = "n_breaks",
label = "Select Item:",
choices = c("item1", "item2", "item3"),
selected = "Item1"),
plotlyOutput(outputId = "main_plot", height = "600px")
)
# Define server logic
server <- function(input, output) {
#Import data
df = read.csv("data/Items.csv")
#Flip data around
df2 <- df %>%
gather(variable, value, -(time:flex_string_2)) %>%
unite(temp, flex_string_2, variable) %>%
group_by(temp) %>%
mutate(id=1:n()) %>%
spread(temp, value)
#Remove the id column
df2 <- subset(df2, select = -c(id))
#Remove "_extra_stuff_on_end" from titles
names(df2) = gsub(pattern = "_extra_stuff_on_end*", replacement = "", x =
names(df2))
#Convert to dataframe
df3 <- as.data.frame(df2)
#Convert factor to datetime
df3$time <- as.character.POSIXt(df3$time, format = "%Y-%m-%d %H:%M:%S")
output$main_plot <- renderPlotly({
plot_ly(df3, x = ~time,
y = df3[, input$n_breaks],
type = 'scatter',
mode = 'lines',
color = df3[, input$n_breaks]) %>%
layout(xaxis = list(type = "category"))
})
}
# Run the application
shinyApp(ui = ui, server = server)
数据框看起来像这4列和26949行:
df
time item1 item2 item3
1 2018-04-09 00:00:06 615 NA NA
2 2018-04-09 00:00:08 NA 465 NA
3 2018-04-09 00:00:08 NA NA NA
4 2018-04-09 00:00:10 NA NA 422
5 2018-04-09 00:00:13 NA NA NA
6 2018-04-09 00:00:21 522 NA 385
7 2018-04-09 00:00:25 NA NA NA
.... .... .... .... ...
26949 2018-04-09 23:59:59 323 NA 200
当我运行此代码时,我得到一个散点图。我真的很想要一个折线图,但是当它运行时它是一个散点图,我得到一个警告,“警告:当跟踪类型是'scatter'或'scattergl'时,数字颜色变量不能(还)映射到行。 “
如果我删除:
type = 'scatter'
我得到一条酒吧。
答案 0 :(得分:0)
我决定使用if else语句保留折线图:
....
#Convert to dataframe
df3 <- as.data.frame(df2)
#Convert factor to datetime
df3$time = strptime(df3$time, '%Y-%m-%d %H:%M:%S')
output$main_plot <- renderPlotly({
if (input$n_breaks == "item1") {
#Create variable X getting rid of NA values
x <- df3$time[!is.na(df3$item1)]
#Convert date to POSIXct for plotly
x = as.POSIXct(x,format="%Y-%m/%d T %H:%M:%S", tz ="UTC")
#Create variable Y getting rid of NA values
y <- df3$item1[!is.na(df3$item1)]
#Plotly plot
plot_ly(x = x, y = y, type = 'scatter', mode = 'lines')
}
else if (input$n_breaks == "item2") {
#Create variable X getting rid of NA values
x <- df3$time[!is.na(df3$item2)]
#Convert date to POSIXct for plotly
x = as.POSIXct(x,format="%Y-%m/%d T %H:%M:%S", tz ="UTC")
#Create variable Y getting rid of NA values
y <- df3$item2[!is.na(df3$item2)]
#Plotly plot
plot_ly(x = x, y = y, type = 'scatter', mode = 'lines')
}
else if (input$n_breaks == "item3") {
#Create variable X getting rid of NA values
x <- df3$time[!is.na(df3$item3)]
#Convert date to POSIXct for plotly
x = as.POSIXct(x,format="%Y-%m/%d T %H:%M:%S", tz ="UTC")
#Create variable Y getting rid of NA values
y <- df3$item3[!is.na(df3$item3)]
#Plotly plot
plot_ly(x = x, y = y, type = 'scatter', mode = 'lines')
}
})
}
# Run the application
shinyApp(ui = ui, server = server)