0

I have a simple data frame in Shiny & would like to make a bar plot with plot_ly that would have conditional coloring based on the values (if profit > 0 green, else red). How to refer to a certain column in the color property?

 data<-reactive({names<-c("Initial", "New")
  revenue<-c(revenue1(),revenue2())
  costs<-c(input$costs, input$costs)
  profit1<-c(profit(), profit2())
  data<-data.frame(names, revenue, costs, profit1)
  data 
  })

  output$profit_bar<-renderPlotly(
    p<-data() %>%
      plot_ly(x = ~names, y = ~revenue, type = 'bar', name = 'Revenue', marker = list(color="#e5f4ea")) %>%
      add_trace(y = ~profit1, name = 'Profit',marker = list(color=ifelse(profit1>0,"#009933","FF6666"))) 

  )

I get an error: object 'profit1' not found. I also tried other options (e.g. data[,4] but no success. Outside shiny, the code is working correct.

Thank you for the answers!

  • Please provide a MWE. See [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), how to create it, that would help us try & get a solution from your data. – massisenergy Dec 12 '18 at 10:46

1 Answers1

0

Ok solved the issue by myself.

  1. I changed the name of the dataframe data -> data_bar (to omit collisions with the function in base R).
  2. Made a reactive color palette outside renderPlotly (profit is the 4th column).:

    col<-reactive({ifelse(data_bar()[,4]>0,"#009933","FF6666")})

  3. Referred to this palette inside renderPlotly.

    output$profit_bar<-renderPlotly(p<-data_bar() %>%
      plot_ly(x = ~names, y = ~revenue, type = 'bar', name = 'Revenue', marker = list(color="#e5f4ea")) %>%
      add_trace(y = ~profit1, name = 'Profit',marker = list(color=col())) 
    

    )