gpt4 book ai didi

r - 如何在不同的ggplot类型之间切换?

转载 作者:行者123 更新时间:2023-12-02 16:21:14 26 4
gpt4 key购买 nike

我想要一个应用程序以不同类型(如线、点、箱线图)绘制我的数据。

让我们考虑一下我的代码:

library(shiny)
library(quantmod)

start <- as.Date("2013-01-01")
end <- as.Date("2016-10-01")
# Apple stock
getSymbols("AAPL", src = "yahoo", from = start, to = end)
apple <- AAPL$AAPL.Close

### Define UI for application
ui <- fluidPage(

# Sidebar panel
sidebarPanel(
selectInput("type",
label = "1. Select plot type",
choices = c("Line" = "geom_line()", "Dot" = "geom_point()", "Boxplot" = "geom_boxplot()"),
selected = 3
)
),

# Main Panel
mainPanel(
plotOutput("sp")
)
)





server <- function(input, output) {
output$sp <- renderPlot({
colm <- as.numeric(apple)
ggplot() +
aes(x = 1:length(colm), y = colm) +
geom_line() +
xlab(NULL)
})
}

# Run the application
shinyApp(ui = ui, server = server)

enter image description here

而且我不确定我在 server 中放置了什么才能在这些不同类型之间切换。我尝试使用 if 语句和 get(input$type) 但是这两个选项都给我错误。

总结 - 我如何编写我的应用程序,以便我可以在不同的绘图类型(线图、点图、箱线图)之间切换,如图所示?

最佳答案

这可以像这样实现。你可以例如使用 switch 语句根据类型分配 geom_xxx

library(shiny)
library(quantmod)
library(ggplot2)

start <- as.Date("2013-01-01")
end <- as.Date("2016-10-01")
# Apple stock
getSymbols("AAPL", src = "yahoo", from = start, to = end)
apple <- AAPL$AAPL.Close

### Define UI for application
ui <- fluidPage(

# Sidebar panel
sidebarPanel(
selectInput("type",
label = "1. Select plot type",
choices = c("Line" = "line", "Dot" = "point", "Boxplot" = "box"),
selected = 3
)
),

# Main Panel
mainPanel(
plotOutput("sp")
)
)

server <- function(input, output) {
output$sp <- renderPlot({
colm <- as.numeric(apple)
geom <- switch(input$type,
line = geom_line(),
point = geom_point(),
box = geom_boxplot()
)
ggplot() +
aes(x = 1:length(colm), y = colm) +
geom +
xlab(NULL)
})
}

# Run the application
shinyApp(ui = ui, server = server)

关于r - 如何在不同的ggplot类型之间切换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65405608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com