在闪亮笔记本中渲染GGPLOT

时间:2019-01-01 13:37:02

标签: r ggplot2 shiny

我是R中的Shiny Notebooks的新手。我只是在四处尝试学习。我正在尝试使ggplot在HTML文档输出中正确显示,但无法正确缩放。如果我在Shiny笔记本中运行相同的ggplot而不使用输入变量,则其外观将达到我的预期。为什么会这样?

以下代码产生的输出不可用:

##GGPLOT Example
```{r}

ggplot(iris, aes(Petal.Length, Sepal.Length, colour = Species)) + 
                xlim(0,10) +
                ylim(0,10) +
                geom_point()
```

以下代码正常工作:

{{1}}

2 个答案:

答案 0 :(得分:1)

您不应该使用aes[[[$提供选项,因为ggplot期望aes中有裸变量名称。对于此实例,提供了aes_string,您可以在其中提供aes的字符串值,该字符串值与selectInput中的shiny很好地配合。

下面的块在带有运行时的笔记本中渲染时应该工作:闪亮

```{r selectInput for iris database, echo = FALSE, message = FALSE}
library(tidyverse)
library(shiny)

selectInput("x_axis", "X-Axis",
            choices = names(iris))

selectInput(inputId = "y_axis", label = "Y-Axis",
            choices = names(iris))

renderPlot({
  ggplot(iris, aes_string(input$x_axis, input$y_axis, colour = "Species")) +
      geom_point()
})
```

答案 1 :(得分:0)

您需要将数据调用到aes()块中,而不仅仅是标题名称。当您调用“ input $ x_axis”时,它将读取为Sepal.Length,但不会提取数据。我在下面提供了一个示例:

renderPlot({
  library(tidyverse)
  data = iris %>%
    select(Species, input$x_axis, input$y_axis)

  ggplot(data, aes(x = data[,2], y = data[,3], colour = Species)) +
      geom_point()
})

旁注:我建议您也清理下拉列表,以便一个不能选择两个相同的列表,也不能选择“物种”。

相关问题