R 如何使用shiny制作交互式图例标签?

R 如何使用shiny制作交互式图例标签?,r,ggplot2,shiny,R,Ggplot2,Shiny,所以,我开始使用shiny并制作交互式绘图。 到目前为止,我已经做了第一次,看起来是这样的: 我在这个情节中使用的代码是 ui <- fluidPage(titlePanel("Suicide Numbers Per 100k"), sidebarLayout(sidebarPanel(selectInput("region","Region",choices = unique(df$Countr

所以,我开始使用shiny并制作交互式绘图。 到目前为止,我已经做了第一次,看起来是这样的:

我在这个情节中使用的代码是

ui <- fluidPage(titlePanel("Suicide Numbers Per 100k"),
                sidebarLayout(sidebarPanel(selectInput("region","Region",choices = unique(df$Country))),
                mainPanel(plotOutput("country100kplot"))))


server <- function(input,output){
  output$country100kplot <- renderPlot(df%>% filter(Country == input$region) %>% ggplot(aes(x=Year,y=Suicides_per_100k,colour=Generation))+geom_line()+labs(x="",y="Suicides",title = "")+theme(plot.title = element_text(hjust = 0.5)))
}

shinyApp(ui,server)

ui当前代码中不会出现这种情况的原因是您需要为plotly对象使用单独的包装器。我无法访问您使用的数据,但以下是我将如何调整您的代码以使其正常工作

需要注意的主要问题是在UI中使用
plotlyOutput()
,在服务器部分使用
renderply

library(shiny)
library(tidyverse)
library(plotly)

ui <- fluidPage(titlePanel("Suicide Numbers Per 100k"),
                sidebarLayout(sidebarPanel(selectInput("region","Region",choices = unique(df$Country))),
                              mainPanel(plotlyOutput("country100kplot"))))


server <- function(input,output){
  output$country100kplot <- renderPlotly({
    
  g <-  df%>% 
      filter(Country == input$region) %>% 
      ggplot(aes(x=Year,y=Suicides_per_100k,colour=Generation))+
      geom_line()+
      labs(x="",y="Suicides",title = "")+
      theme(plot.title = element_text(hjust = 0.5))
    
  g <- ggplotly(g)
    })
}

shinyApp(ui,server)

库(闪亮)
图书馆(tidyverse)
图书馆(绘本)

ui这在当前代码中不会出现的原因是您需要为plotly对象使用单独的包装器。我无法访问您使用的数据,但以下是我将如何调整您的代码以使其正常工作

需要注意的主要问题是在UI中使用
plotlyOutput()
,在服务器部分使用
renderply

library(shiny)
library(tidyverse)
library(plotly)

ui <- fluidPage(titlePanel("Suicide Numbers Per 100k"),
                sidebarLayout(sidebarPanel(selectInput("region","Region",choices = unique(df$Country))),
                              mainPanel(plotlyOutput("country100kplot"))))


server <- function(input,output){
  output$country100kplot <- renderPlotly({
    
  g <-  df%>% 
      filter(Country == input$region) %>% 
      ggplot(aes(x=Year,y=Suicides_per_100k,colour=Generation))+
      geom_line()+
      labs(x="",y="Suicides",title = "")+
      theme(plot.title = element_text(hjust = 0.5))
    
  g <- ggplotly(g)
    })
}

shinyApp(ui,server)

库(闪亮)
图书馆(tidyverse)
图书馆(绘本)

ui尝试另一个更具交互性的库,如plotly。这也可能有助于如何整合到Shiny中。啊,用ggplot2是没有办法的?你可以把ggplot转换成plotly对象,但在我看来,它并不总是很好看。也许可以看看这个包
ggiraph
。它建立在ggplot2的基础上,我认为它看起来很光滑。我没有足够的经验来回答这个问题。我有一些问题。检查我的编辑可能需要使用
plotly::renderPlotly()
而不是
renderPlot()
,但很难说。请尝试另一个更具交互性的库,如plotly。这也可能有助于如何整合到Shiny中。啊,用ggplot2是没有办法的?你可以把ggplot转换成plotly对象,但在我看来,它并不总是很好看。也许可以看看这个包
ggiraph
。它建立在ggplot2的基础上,我认为它看起来很光滑。我没有足够的经验来回答这个问题。我有一些问题。检查我的编辑可能需要使用
plotly::renderPlotly()
而不是
renderPlot()
,但很难说。