[英]Aesthetics must be either length 1 or the same as the data (1): colour
I am trying to plot a graph that will change based on selected inputs. 我正在尝试绘制一个将根据所选输入进行更改的图表。 Moreover, the data in the graph should be categorized by state.
此外,图中的数据应按州分类。 The dataset that I am using is
midwest
which is from ggplot2
. 我使用的数据集是
midwest
,来自ggplot2
。 For some reason, the color which should be based off of the state from the midwest
dataset is not working. 出于某种原因,应该基于来自
midwest
数据集的状态的颜色不起作用。 I get the error when I try to use color = state
or color = prof_poverty$state
. 当我尝试使用
color = state
或color = prof_poverty$state
时,我收到错误。 Aesthetics must be either length 1 or the same as the data (1): colour
. Aesthetics must be either length 1 or the same as the data (1): colour
。 There should be 5 different colors since there are 5 different states. 应该有5种不同的颜色,因为有5种不同的状态。
This is my code: 这是我的代码:
UI UI
library(shiny)
library(dplyr)
library(ggplot2)
prof_poverty <- midwest %>%
select(state, county, percprof, percadultpoverty, percpovertyknown, percbelowpoverty, percadultpoverty, percelderlypoverty, percchildbelowpovert)
ui <- fluidPage(
pageWithSidebar(
headerPanel('Poverty compared with number of professors'),
sidebarPanel(
selectInput('xcol', 'X variable', names(prof_poverty)[3:8]),
selectInput('ycol', 'Y variable', names(prof_poverty)[3:8]),
selected = names(prof_poverty)[[2]]
),
mainPanel(
plotOutput('poverty')
)
)
)
SERVER 服务器
# Define server that renders a map and a table
server <- function(input, output){
# Combine the selected variables into a new data frame
selectedData <- reactive({
prof_poverty[input$xcol, input$ycol]
})
output$poverty <- renderPlot ({
ggplot(data = selectedData(), aes(x = input$xcol, y = input$ycol)) +
geom_point(aes(color = prof_poverty$state)) })
}
# sRun the application
shinyApp(ui = ui, server = server)
Just changing the data used in the ggplot call to prof_poverty
and using aes_string
should work. 只需将ggplot调用中使用的数据更改为
prof_poverty
并使用aes_string
。 (although there are more modern ways to deal with this) (虽然有更现代的方法来处理这个)
The way you have subset the data in your reactive selectedData
hasn't worked and the use of the full vector of states in the colour aesthetic is triggering the error. 在反应性
selectedData
对数据进行子集化的方式没有奏效,并且在颜色美学中使用完整的状态向量会触发错误。
Given the renderPlot
function is reactive, you don't really need a reactive data object selectedData
created before this anyway. 鉴于
renderPlot
函数是被动的,你实际上并不需要在此之前创建的被动数据对象selectedData
。
server <- function(input, output){
output$poverty <- renderPlot ({
ggplot(data = prof_poverty, aes_string(x = input$xcol, y = input$ycol)) +
geom_point(aes(color = prof_poverty$state)) })
}
# Run the application
shinyApp(ui = ui, server = server)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.