【问题标题】:shiny: plotting selected columns from dataset to graphs闪亮:将选定的列从数据集中绘制到图形
【发布时间】:2014-09-23 17:18:14
【问题描述】:

只是发现了闪亮的应用程序,但这让我发疯了......我查看了许多 server.R 和 ui.R 代码的示例,但无法弄清楚我做错了什么。如果这是非常基本的事情,请提前道歉............

以 iris 数据集为例,我想将一列与另一列进行对比,使用 qplot 或者最好是 ggplot 进行一些简单的操作

但是,使用 qplot 我得到了这个:

并使用 ggplot2,我得到了错误:

我认为我不需要响应函数,因为我没有对数据集进行子集化,只是提取要绘制的列。

server.R 代码

library(shiny)
library(shinyapps)
library(ggplot2)

shinyServer(function(input, output, session) {

    output$text1 <- renderText({input$id1})

    output$text2 <- renderText({input$select1})

    output$plot1 <- renderPlot({
            g <- qplot(Sepal.Length, input$select1, data = iris)
            print(g)
    })

})

或者使用ggplot函数代替qplot调用

            g <- ggplot(iris, aes(x = Sepal.Length, y = input$select1)) 
            g <- g + geom_line(col = "green", lwd =1) + 
                    labs(x = "Date", y = "Ranking") + 
                    theme_bw() + scale_y_reverse()

ui.R 代码

library(shiny)
library(shinyapps)
data(iris)
opts <- unique(colnames(iris))
opts <- opts[-1] ## want to keep Sepal.Length as the x values

shinyUI(pageWithSidebar(
    headerPanel('test with iris database'),
    sidebarPanel(
            selectInput(inputId = "select1", label = "select", 
                        choices = opts),
            textInput(inputId = "id1", label = "Input Text", "")
    ),
    mainPanel(
            p('Output text1'),
            textOutput('text1'),
            textOutput('text2'),
            plotOutput('plot1')
    )
))

【问题讨论】:

    标签: r shiny shiny-server


    【解决方案1】:

    将您的 aes 语句更改为 aes_string 并将 x 设为字符串。这应该可以解决问题。

    g <- ggplot(iris, aes_string(x = "Sepal.Length", y = input$select1)) 
    g <- g + geom_line(col = "green", lwd =1) +
         labs(x = "Date", y = "Ranking") + 
         theme_bw() + scale_y_reverse()
    

    【讨论】:

    • 谢谢查尔斯,这解决了我的问题。我假设需要 aes_string 因为 input$select1 的返回是一个字符串?我曾尝试使用 as.name 将 input$select1 定义为非字符,但这对我不起作用。
    • @laoisman,说实话,我并不完全确定内部是什么。这个答案来自经验和文档向我展示的内容。如果你好奇,我建议联系 Shiny 包的维护者。抱歉,我无法回答您的后续问题。
    猜你喜欢
    • 2020-08-10
    • 2019-11-11
    • 1970-01-01
    • 2021-01-31
    • 2019-09-25
    • 2019-06-15
    • 2020-05-08
    • 2017-10-13
    • 2018-11-16
    相关资源
    最近更新 更多