r基于选定列的ggplot2堆叠式条形图

时间:2018-10-25 18:37:17

标签: r ggplot2 shiny

在我闪亮的应用程序中,我想根据从下拉菜单中选择的指标绘制堆积的条形图。

我有3个数字列:客户编号,交易编号和已付款金额。

在下拉菜单(metrics_type)中,我可以选择任何一个。我的条形图将相应更改。

在线建议的一种方法是将所有指标放在一列中,然后过滤属于该指标的行。

我尝试将指标分开。我选择因素列和指标列,然后更改指标列的名称。

我不断收到错误消息“列{​​{1}}必须具有唯一的名称”。我不知道怎么了。

我是新来的闪亮人士。任何建议将不胜感激。

问候

Bing

============================

以下是简化代码:

weight_metrics

数据在这里:

library(shiny)
library(ggplot2)
library(dplyr)
library(DT)

summary_1 <- read.csv("summary_1.csv")

ui <- fluidPage(
  selectInput(inputId = 'var_type', label = NULL,
              choices = c("Gender", "Age Group"),
              selected = "Overall",
              width = '250px'),

  selectInput(inputId = 'metrics_type', label = NULL,
              choices = c("# Customer" = "numb_ctm", 
                          "# Transaction" = "numb_trn", 
                          "$ Cost" = "tot_amt_pd"),
              selected = "tot_amt_pd",
              width = '250px'),

  DT::dataTableOutput("monthly_sum"),
  plotOutput("monthly_comparison")
)

server <- function(input,output) {

  data1 <- reactive({
    temp <- summary_1 %>%
      select(din_month, category, input$metrics_type)

    colnames(temp)[-1] <- "weight_metrics"

    temp <- temp %>%
      filter(var_type = input$var_type)
  })

  output$monthly_sum <- DT::renderDataTable(
    DT::datatable(
      data1(),
      options = list(order = list(1, 'desc')),
      rownames = FALSE,
      colnames = c('Month', 'Group', 'metrics_type')
    )
  )

  output$monthly_comparison <- renderPlot({
      ggplot(data1(), aes(din_month)) + 
      geom_bar(aes(weight = weight_metrics, fill = category))  }
  )
}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:1)

我发现了我的错误:

我使用colnames(temp)[-1] <- "weight_metrics"

更改列名

此行实际上将除姓氏之外的所有列更改为weight_metrics。 :-(

我将其更改为

names(temp)[length(names(temp))]<-"weight_metrics"

现在代码可以使用了。