【发布时间】:2018-12-07 17:47:08
【问题描述】:
我有以下 Shiny 应用程序,它使用带有 5 个下拉选项的 Plotly 显示时间序列折线图。这可行,但我想在每个选择的顶部附近添加一个自定义标题。有没有一种简单的方法可以添加到这个应用程序中,如果有,我应该在哪里添加它?
#Import libraries
library(shiny)
library(plotly)
library(tidyr)
library(bindrcpp)
# Define UI for application that draws a histogram
ui <- bootstrapPage(
selectInput(inputId = "n_breaks",
label = "Select Data:",
choices = c("Distinct_FLD","Not_On_MM","API_Call_Count","Cost","CACHE_Count"),
selected = "Distinct_FLD"),
plotlyOutput(outputId = "main_plot", height = "600px")
)
# Define server logic required to draw a histogram
server <- function(input, output) {
#Import data
df = read.csv("API_Statistics.csv")
output$main_plot <- renderPlotly({
if (input$n_breaks == "Distinct_FLD") {
#Create variable X getting rid of NA values
x <- df$Date[!is.na(df$Distinct_FLD)]
#Create variable Y getting rid of NA values
y <- df$Distinct_FLD[!is.na(df$Distinct_FLD)]
#Plotly plot
plot_ly(x = x, y = y, type = 'scatter', mode = 'lines')
}
else if (input$n_breaks == "Not_On_MM") {
#Create variable X getting rid of NA values
x <- df$Date[!is.na(df$Not_On_MM)]
#Create variable Y getting rid of NA values
y <- df$Not_On_MM[!is.na(df$Not_On_MM)]
#Plotly plot
plot_ly(x = x, y = y, type = 'scatter', mode = 'lines')
}
else if (input$n_breaks == "API_Call_Count") {
#Create variable X getting rid of NA values
x <- df$Date[!is.na(df$API_Call_Count)]
#Create variable Y getting rid of NA values
y <- df$API_Call_Count[!is.na(df$API_Call_Count)]
#Plotly plot
plot_ly(x = x, y = y, type = 'scatter', mode = 'lines')
}
else if (input$n_breaks == "Cost") {
#Create variable X getting rid of NA values
x <- df$Date[!is.na(df$Cost)]
#Create variable Y getting rid of NA values
y <- df$Cost[!is.na(df$Cost)]
#Plotly plot
plot_ly(x = x, y = y, type = 'scatter', mode = 'lines')
}
else if (input$n_breaks == "CACHE_Count") {
#Create variable X getting rid of NA values
x <- df$Date[!is.na(df$CACHE_Count)]
#Create variable Y getting rid of NA values
y <- df$CACHE_Count[!is.na(df$CACHE_Count)]
#Plotly plot
plot_ly(x = x, y = y, type = 'scatter', mode = 'lines')
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
有没有一种简单的方法可以为这个应用程序中的每个图表添加自定义标题,如果可以,我应该在哪里添加它?
【问题讨论】:
-
您正在动态(反应性)创建这些图,这意味着在 ui 中使用 html 标记很可能不起作用。也许您应该做的是为每个图表动态创建一个标题(可能在相应的“
if语句下)并使用renderText将其输出到相应的h_(textOutput("Title"))。这样当图表发生变化时,renderText函数将能够动态创建新标题并将其输出到 UI。注意textOutput可以直接放在plotlyOutput上方 -
我会试试@Chabo
-
另一种选择是使用
plot_ly(your_code) %>% layout(title = "myTitle")直接在图表中定义标题。有关示例,请参见 this。