簡體   English   中英

美學必須是長度1或與數據(1)相同:顏色

[英]Aesthetics must be either length 1 or the same as the data (1): colour

我正在嘗試繪制一個將根據所選輸入進行更改的圖表。 此外,圖中的數據應按州分類。 我使用的數據集是midwest ,來自ggplot2 出於某種原因,應該基於來自midwest數據集的狀態的顏色不起作用。 當我嘗試使用color = statecolor = prof_poverty$state時,我收到錯誤。 Aesthetics must be either length 1 or the same as the data (1): colour 應該有5種不同的顏色,因為有5種不同的狀態。

這是我的代碼:

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')
       )
   )
)

服務器

# 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)

只需將ggplot調用中使用的數據更改為prof_poverty並使用aes_string (雖然有更現代的方法來處理這個)

在反應性selectedData對數據進行子集化的方式沒有奏效,並且在顏色美學中使用完整的狀態向量會觸發錯誤。

鑒於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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM