R Shiny:为什么 ggplot 不起作用?
R Shiny: Why doesn't ggplot work?
我正在尝试使用 ggplot2 为以下数据绘制图表:
data
Name date weight height
Cat1 2016-03-01 34.20000 22.50000
Cat1 2016-04-01 35.02080 23.01750
Cat1 2016-05-01 35.86130 23.54690
Cat1 2016-06-01 36.72197 24.08848
Cat2 2016-03-01 33.55000 22.96000
Cat2 2016-04-01 33.61710 23.41920
Cat2 2016-05-01 33.68433 23.88758
Cat2 2016-06-01 33.75170 24.36534
我使用的代码:
library("shiny")
library("xlsx")
library("ggplot2")
animal <- read.xlsx("C:\data\animals.xlsx",1)
ui<- fluidPage(
titlePanel("Animals"),
sidebarLayout(
sidebarPanel(
helpText("Create graph of height or weight animals"),
selectInput("anim",
label = "Choose an animal",
choices = c("Cat1", "Cat2"),
selected = "Cat1"),
selectInput("opti",
label = "Option",
choices = c("weight", "height"),
selected = "weight")
),
mainPanel(plotOutput("graph"))
))
server <- function(input, output){
output$graph <- renderPlot({
p2 <- ggplot(subset(animal, Name %in% input$anim)) + geom_line(aes(x=date, y = input$opti))
print(p2)
})
}
shinyApp(ui=ui, server= server)
我没有收到错误,但绘图的输出只是一条直线 (plot)。我不明白为什么,如果我将代码放在命令 window 和 ggplot
中,它确实有效。
由于您的 y 美学是用户提供的输入而不是硬编码的 R 标识符,因此您需要使用 aes_string
而不是 aes
:
p2 = ggplot(subset(animal, Name %in% input$anim)) +
geom_line(aes_string(x = 'date', y = input$opti))
请注意,您现在需要引用 x 审美。
旁注:您可以 print
ggplots,但我总是觉得很奇怪:打印绘图是什么意思?1 plot
相反:
plot(p2)
效果一样,只是看起来更合乎逻辑。
1 记录一下,我知道为什么ggplot2提供了一个print
函数。这是一个巧妙的技巧。明确地调用它是没有意义的。
我正在尝试使用 ggplot2 为以下数据绘制图表: data
Name date weight height
Cat1 2016-03-01 34.20000 22.50000
Cat1 2016-04-01 35.02080 23.01750
Cat1 2016-05-01 35.86130 23.54690
Cat1 2016-06-01 36.72197 24.08848
Cat2 2016-03-01 33.55000 22.96000
Cat2 2016-04-01 33.61710 23.41920
Cat2 2016-05-01 33.68433 23.88758
Cat2 2016-06-01 33.75170 24.36534
我使用的代码:
library("shiny")
library("xlsx")
library("ggplot2")
animal <- read.xlsx("C:\data\animals.xlsx",1)
ui<- fluidPage(
titlePanel("Animals"),
sidebarLayout(
sidebarPanel(
helpText("Create graph of height or weight animals"),
selectInput("anim",
label = "Choose an animal",
choices = c("Cat1", "Cat2"),
selected = "Cat1"),
selectInput("opti",
label = "Option",
choices = c("weight", "height"),
selected = "weight")
),
mainPanel(plotOutput("graph"))
))
server <- function(input, output){
output$graph <- renderPlot({
p2 <- ggplot(subset(animal, Name %in% input$anim)) + geom_line(aes(x=date, y = input$opti))
print(p2)
})
}
shinyApp(ui=ui, server= server)
我没有收到错误,但绘图的输出只是一条直线 (plot)。我不明白为什么,如果我将代码放在命令 window 和 ggplot
中,它确实有效。
由于您的 y 美学是用户提供的输入而不是硬编码的 R 标识符,因此您需要使用 aes_string
而不是 aes
:
p2 = ggplot(subset(animal, Name %in% input$anim)) +
geom_line(aes_string(x = 'date', y = input$opti))
请注意,您现在需要引用 x 审美。
旁注:您可以 print
ggplots,但我总是觉得很奇怪:打印绘图是什么意思?1 plot
相反:
plot(p2)
效果一样,只是看起来更合乎逻辑。
1 记录一下,我知道为什么ggplot2提供了一个print
函数。这是一个巧妙的技巧。明确地调用它是没有意义的。