R语言 在Shiny应用程序中未显示绘图图表

3j86kqsm  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(186)

我尝试在一个简单的Shiny应用程序中实现一个带有下拉菜单的选项。通过这个下拉列表,您可以在两个图表之间进行选择。第一个图表是使用ggplot2库准备的,而第二个图表是使用Plotly库准备的。下面是我的代码:

---
title: "Test App"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(tidyverse)
library(plotly)

# Data
data <- mtcars
data$cyl <- as.factor(data$cyl)

Column {.sidebar}

selectInput("clusterNum",
  label = h4("Charts"),
  choices = list("Chart1" = "Chart1", "Chart2" = "Chart2"),
  selected = "Chart1"
)

Column {data-width=650}

Chart

Chart1 <- ggplot(data, aes(x = wt, y = mpg)) +
  geom_point()

Chart2 <- plot_ly(data, x = ~wt, y = ~mpg, type = 'bar')

renderPlot({
  switch(input$clusterNum,
    "Chart1" = Chart1,
    "Chart2" = Chart2
  )
})

执行完这段代码后,我看到用ggplot2准备的图表1可以正常工作,而用Plotly准备的图表2**没有显示**,那么谁能帮我解决这个问题,用下拉列表选择后看到图表2呢?
8ehkhllq

8ehkhllq1#

要渲染plotly图表,必须使用renderPlotly,而对于ggplot,我们必须坚持使用renderPlot。因此,在两个渲染函数之间有条件地切换需要更多的工作,并涉及到 Package renderUI和通过uiOutput显示图表:

---
title: "Test App"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(tidyverse)
library(plotly)

# Data
data <- mtcars
data$cyl <- as.factor(data$cyl)

Column {.sidebar}

selectInput("clusterNum",
  label = h4("Charts"),
  choices = list("Chart1" = "Chart1", "Chart2" = "Chart2"),
  selected = "Chart1"
)

Column {data-width=650}

Chart

Chart1 <- ggplot(data, aes(x = wt, y = mpg)) +
  geom_point()

Chart2 <- plot_ly(data, x = ~wt, y = ~mpg, type = 'bar')
observeEvent(input$clusterNum, {
  output$plot <- switch(input$clusterNum,
    "Chart1" = renderUI({renderPlot(Chart1)}),
    "Chart2" = renderUI({renderPlotly(Chart2)})
  )
})

uiOutput("plot")

![](https://i.stack.imgur.com/x6rgI.png)

相关问题