首页 > 解决方案 > 有条件的着色情节闪亮

问题描述

我在 Shiny 中有一个简单的数据框,想用 plot_ly 制作一个条形图,它会根据值进行条件着色(如果利润 > 0 绿色,否则为红色)。如何引用颜色属性中的某一列?

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

  )

我收到一个错误: 找不到对象“profit1”。 我还尝试了其他选项(例如 data[,4] 但没有成功。在闪亮之外,代码工作正常。

谢谢你的回答!

标签: rshinybar-chartplotlyreactive

解决方案


好的,我自己解决了这个问题。

  1. 我更改了数据框数据的名称 -> data_bar(以省略与基础 R 中的函数的冲突)。
  2. 在 renderPlotly 之外制作了一个反应调色板(利润是第 4 列)。:

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

  3. 在 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())) 
    

    )


推荐阅读