ggplot of aggregated data frame is missing values

2019-08-25 01:56发布

I'm trying to ggplot some consolidated data but unfortunately I'm having some loss...

df <-   Project    Subproject       Value      Date  
                 A           1              47      2017-08-04
                 A           2              22      2017-08-04
                 B           1              1       2017-08-04
                 A           1              40      2017-08-07
                 A           2              29      2017-08-07
                 B           1              1       2017-08-07

new_df <- df %>%
          group_by(Project, Date)%>%
          summarise(Value = sum(Value))


ui <- dashboardPage(
      dashboardSidebar(
        sidebarMenu(
        menuItem('Dashboard', tabName = 'dashboard', icon = icon('dashboard')),

  menuItem(
    dateRangeInput('date_range', label = "Date Range",format = "mm/dd/yyyy", start = Sys.Date()-17, end = Sys.Date()+17, startview = "month", weekstart = 0, separator = " to ", width = 200)
  ),


  menuItem(
    checkboxGroupInput('project_name', label = "Project", choices = c(unique(new_df$Project)), selected = c(unique(new_df$Project)))

  ),

  menuItem(
    submitButton(text = "Apply Changes", icon = NULL, width = NULL)
  )
)
),

dashboardBody(

fluidRow(
  box(plotOutput("plot1", width = 1000, height = 500))
)
)

server <- function(input, output) {


output$plot1 <- renderPlot({


date_data <- reactive({
  subset(new_df, Date >= input$date_range[1] & Date <= input$date_range[2])
})


project_data <- reactive({
  subset(date_data(), Project %in% input$project_name)
})




ggplot(data = project_data(), aes(x = Date, y = value, fill = Project)) +
  geom_bar(stat = 'identity') +
  geom_hline(yintercept = 49, linetype = 'dotted', color = 'red', size = 0.8) + 
  geom_hline(yintercept = 70, linetype = 'dashed', color = 'purple', size = 0.8) +
  geom_text(data = project_data(), aes(label = value, fill = Project), size=4, position = position_stack(vjust = 0.5)) + 

 })
}
shinyApp(ui, server) 

As you can see from the photos, the first picture is my geom_bar without aggregating/summarising data, and the second is with aggregating/summarising. Project B is not showing up at all in the second one, despite supposedly still being in the dataframe... and without summarising in the first graph, my geom_text is still displaying non-aggregated numbers by subproject.

graphs

1条回答
Summer. ? 凉城
2楼-- · 2019-08-25 02:11

Figured it out... Turns out that some of my values were actually NA instead of 0, which was messing up how the list was aggregating. fixed with this line:

df$Value = ifelse(is.na(df$Value), 0, df$Value)
查看更多
登录 后发表回答