r - 闪亮的散点图
问题描述
我正在尝试根据已加载的 csv 创建散点图,但是当我运行代码时,当我包含 aes 映射时,要么没有显示绘图,要么出现错误:“应该使用aes()
or创建映射aes_()
。”
谁能给我指点我哪里出错了?
代码:
library(shiny)
library(ggplot2)
ui <- (fluidPage(
titlePanel("Pig Breeds"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "x",
label = "Pig Breeds:",
choices = c("total_pigs", "female_breeding_herd",
"in_pig_sows", "in_pig_gifts", "other_sows",
"maiden_gilts", "boars_for_service", "other_pigs"),
selected = "total_pigs"),
selectInput(inputId = "y",
label = "Year by year change:",
choices = c(2016, 2017, 2018, "year_on_year_change"),
selected = 2016),
actionButton(inputId = "update", label = "update")
),
mainPanel = (
plotOutput(outputId = "scatterplot")
)
)
)
)
server <- (function(input, output) {
output$scatterplot <- renderPlot({
ggplot(data=(read.csv("eu_pigs.csv")),
aes(x = output$x, y = output$y) +
geom_point())
observeEvent(input$update, {print(as.numeric(input$update))})
}
)
}
)
shinyApp(ui, server)
解决方案
正如错误消息所说,您使用aes
不正确。该函数采用列名,而不是变量引用。也就是说,更换
aes(x = output$x, y = output$y)
经过
aes(x = x, y = y)
或者,您更有可能希望能够从输入中控制绘图,因此您希望使用
aes_string(x = input$x, y = input$y)
您的代码中还有很多杂散的括号和大括号。删除那些。此外,mainPanel
是您需要调用的函数。相反,您的代码正在为其分配一些东西。
最后,你实际上需要绘制你的情节。在所有这些事情都修复之后,相关代码如下所示:
ui <- fluidPage(
titlePanel("Pig Breeds"),
sidebarLayout(
sidebarPanel(…),
mainPanel(
plotOutput(outputId = "scatterplot")
)
)
)
server <- function(input, output) {
output$scatterplot <- renderPlot({
p = ggplot(data = read.csv("eu_pigs.csv")) +
aes_string(x = input$x, y = input$y) +
geom_point()
plot(p)
observeEvent(input$update, print(as.numeric(input$update)))
})
}
如果绘图对象是您在函数中执行的最后一件事renderPlot
,您可以省略plot
:
output$scatterplot <- renderPlot({
ggplot(data = read.csv("eu_pigs.csv")) +
aes_string(x = input$x, y = input$y) +
geom_point()
})
推荐阅读
- kubernetes - 来自节点而不是 LB 服务的 GKE 集群出口流量
- javascript - D3 Sankey 链接缩放问题
- authentication - React-admin:在 checkAuth 失败时不显示警告消息
- python - Threadpool 在 python 中再创建 4 个线程
- c# - subject.Dispose() 与 subject.OnCompleted()
- python - DataFrame 创建奇怪的数据结构
- c# - 如何设计没有 TabControl 的 TabPage?
- html - 如何在 Javascript 中编写多个条件以更改班级?
- javascript - Vue JS error 解析错误:Unexpected token - 错误绝对没用
- spring - CustomAuthenticationProvider 不会被称为 spring-security 5.2