Отображение данных графика во всплывающей подсказке ggvis

У меня есть блестящее приложение, которое обновляет точечную диаграмму на основе пользовательского ввода для переменных x и y. Я хочу иметь данные для x и y во всплывающей подсказке и иметь это обновление, когда пользователь обновляет то, что он хочет по осям x и y. Ниже приведен пример кода с двумя моими попытками решить эту проблему (вторая попытка закомментирована). Обратите внимание, что я добавил в набор данных Iris, чтобы дать каждой точке данных уникальный идентификатор на основе номера строки в наборе данных.

#Check packages to use in library
{
library('shiny') #allows for the shiny app to be used
library('stringr') #string opperator
library('ggvis') #allows for interactive ploting
library('dplyr')
library('RSQLite')
}

alldata <- iris

#adds a column of a unique ID for each row
alldata$ID <- 1:nrow(alldata)

# UI

ui<-fluidPage(
titlePanel("Iris"),
fluidRow(
column(12,
       ggvisOutput("plot1")
),
column(4,
       wellPanel(
         h4("Data Variables"),
         selectInput(inputId = "x", label="Select x-axis Variable:", choices=as.character(names(alldata[,1:4])),selected='Petal.Length', multiple = FALSE),
         selectInput(inputId = "y", label="Select y-axis Variable:", choices=as.character(names(alldata[,1:4])),selected='Petal.Width', multiple = FALSE)
       ))
))

#SERVER
server<-function(input,output,session)
{
# Function for generating tooltip text
my_tooltip <- function(tt) {
if (is.null(tt)) return(NULL)
if (is.null(tt$ID)) return(NULL)

# Pick out the shot with this ID
alldata <- isolate(alldata)
Datapoint <- alldata[alldata$ID == tt$ID, ]

paste0("<b>", "Species: ", Datapoint$`Species`, 
       "</b><br>", "ID: ", Datapoint$`ID`,
       "<br>", "X Variable: ", Datapoint$`input$x`,
       "<br>", "Y Variable: ", Datapoint$`input$y`
       # "<br>", "X Variable: ", Datapoint %>% `input$x`,
       # "<br>", "Y Variable: ", Datapoint %>% `input$y`
)
}

vis <- reactive({

xvar <- prop("x", as.symbol(input$x))
yvar <- prop("y", as.symbol(input$y))

p1 = alldata %>%
  ggvis(x = xvar, y = yvar) %>%
  layer_points(size.hover := 200,
               fillOpacity:= 0.5, fillOpacity.hover := 1,
               fill = ~Species,
               key := ~ID
  ) %>%

  # Adds the previously defined tool_tip my_tooltip
  add_tooltip(my_tooltip, "hover")

  # Specifies the size of the plot
  # set_options(width = 800, height = 450, duration = 0)
})

#Actually plots the data
vis %>% bind_shiny("plot1")
}

#Run the Shiny App to Display Webpage
shinyApp(ui=ui, server=server)

person User247365    schedule 08.07.2016    source источник


Ответы (1)


Одним из вариантов является подмножество только интересующих столбцов в вашей функции всплывающей подсказки, а затем отображение всех значений из этого набора данных.

my_tooltip <- function(tt) {
        if (is.null(tt)) return(NULL)
        if (is.null(tt$ID)) return(NULL)

        Datapoint <- alldata[alldata$ID == tt$ID, c("Species", "ID", input$x, input$y)]

        paste0(names(Datapoint), ": ", format(Datapoint), collapse = "<br />")
    }

Или просто используйте, например, input$x напрямую, так как это символы, которые легко извлечь из наборов данных и использовать в качестве имен всплывающих подсказок.

my_tooltip <- function(tt) {
        if (is.null(tt)) return(NULL)
        if (is.null(tt$ID)) return(NULL)

        Datapoint = alldata[alldata$ID == tt$ID, ]

        paste0("<b>", "Species: ", Datapoint$`Species`,
              "</b><br>", "ID: ", Datapoint$`ID`,
              "<br>", input$x, ": ", Datapoint[[input$x]],
              "<br>", input$y, ": ", Datapoint[[input$y]])
    }
person aosmith    schedule 08.07.2016
comment
Спасибо, я попробовал только ваше второе решение, так как его было проще всего реализовать с тем, что у меня уже было, и оно работало именно так, как я хотел! - person User247365; 12.07.2016