我正在尝试使用ggplot2而不是基本R的plot函数进行renderplot。
但是在ggplot2中使用反应性数据集时遇到了一些问题。
以下是适用于基数R的绘图的代码:
library(shiny)
library(ggplot2)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Javier Test"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
# Input: Select a file ----
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
# Horizontal line ----
tags$hr(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"'),
#implementing dropdown column
selectInput('xcol', 'X Variable', ""),
selectInput('ycol', 'Y Variable', "", selected = "")),
# Show a plot of the generated distribution
mainPanel(
# Output: Data file ----
plotOutput('MyPlot')
)
)
)
# Define server logic required to draw a histogram
server <- shinyServer(function(input, output, session) {
# added "session" because updateSelectInput requires it
data <- reactive({
req(input$file1) ## ?req # require that the input is available
inFile <- input$file1
# tested with a following dataset: write.csv(mtcars, "mtcars.csv")
# and write.csv(iris, "iris.csv")
df <- read.csv(inFile$datapath, header = input$header, sep = input$sep,
quote = input$quote)
# Update inputs (you could create an observer with both updateSel...)
# You can also constraint your choices. If you wanted select only numeric
# variables you could set "choices = sapply(df, is.numeric)"
# It depends on what do you want to do later on.
updateSelectInput(session, inputId = 'xcol', label = 'X Variable',
choices = names(df), selected = names(df))
updateSelectInput(session, inputId = 'ycol', label = 'Y Variable',
choices = names(df), selected = names(df)[2])
return(df)
})
output$MyPlot <- renderPlot({
x <- data()[,c(input$xcol, input$ycol)]
plot(x)
})
})
shinyApp(ui, server)
这是我尝试改为ggplot2渲染图的部分:
output$MyPlot <- renderPlot({
ggplot(data, aes(x=input$xcol, y=input$ycol)) + geom_point()
})
错误:ggplot2不知道如何处理reactExpr / reactive类的数据
任何想法我如何对ggplot2使用反应性数据集?
非常感谢您!
更新
这是代码!我知道了。不是很好,有没有更好的表示方法?
output$MyPlot <- renderPlot({
x <- data()[,c(input$xcol, input$ycol)]
ggplot(x, aes(x=x[,1], y=x[,2])) + geom_point()
})
答案 0 :(得分:1)
现在效果很好:
output$MyPlot <- renderPlot({
x <- data()[,c(input$xcol, input$ycol)]
ggplot(x, aes(x=data()[,c(input$xcol)],
y=data()[,c(input$ycol)])) + geom_point()
})
答案 1 :(得分:1)
您可以使用renderPlot
包中的aes
函数,而不是使用aes_string
函数多次设置数据,而不是使用ggplot
函数。因此,一种内衬解决方案将是:
output$MyPlot <- renderPlot({
ggplot(data = data(), aes_string(x = input$xcol, y = input$ycol)) + geom_point()
})