r - 有条件的着色情节闪亮
问题描述
我在 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] 但没有成功。在闪亮之外,代码工作正常。
谢谢你的回答!
解决方案
好的,我自己解决了这个问题。
- 我更改了数据框数据的名称 -> data_bar(以省略与基础 R 中的函数的冲突)。
在 renderPlotly 之外制作了一个反应调色板(利润是第 4 列)。:
col<-reactive({ifelse(data_bar()[,4]>0,"#009933","FF6666")})
在 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()))
)
推荐阅读
- android - 带有未生成参数的android NavDirections构造函数
- flutter - 为什么颤振在运行时显示多个过去的错误?
- apache-spark - 在pyspark中添加数据类型为字符串格式的两列的值
- registry - Chromium 策略:我的 PC 和 VM Ware 的差异
- jboss - Drools-如何获得触发规则的事实?
- django - Django is_valid() 总是返回 false 错误
- java - Spring Data MongoDB 视图
- pandas - 两列的 iterrows() 并将结果保存在一列中
- python - 未保存用户信息
- ssl-certificate - 已处理的证书链,但在信任提供者不信任的根证书中终止。(错误 0x800b0109)