【问题标题】:Plotly - Two colors mix to one color but should not when using color labelsPlotly - 两种颜色混合为一种颜色,但在使用颜色标签时不应该
【发布时间】:2021-04-06 11:55:17
【问题描述】:

我有一个条形图,应该将 0 以上的条着色为红色,将 0 以下的条着色为绿色。如果我的数据包含数字 + - 0,这可以正常工作。

library(ggplot2)
library(plotly)

    set.seed(1)
plot1 <- data.frame(category = as.factor(seq(10)), diff = runif(10, min=-50, max=50)) %>% # negative and positive numbers
  mutate(label = ifelse(diff <= 0, "green", "red")) %>% 
plot_ly(x=~diff, y=~category, type = 'bar', orientation = 'h', 
        color = ~label, colors = c("#009C48", "#E61414")) 

plot1

但是,由于此图在闪亮的应用程序中使用并且数据会有所不同,因此有时数据仅包含数字 + - 0

然后,两种颜色混合在一起变成难看的棕色。喜欢这里:

set.seed(1)
plot2 <- data.frame(category = as.factor(seq(10)), diff = runif(10, min=20, max=50)) %>% # only positive numbers
  mutate(label = ifelse(diff <= 0, "green", "red")) %>% 
  plot_ly(x=~diff, y=~category, type = 'bar', orientation = 'h', 
          color = ~label, colors = c("#009C48", "#E61414")) 

plot2

在图 2 中,条形应为红色,因为所有条形均高于 0。 任何人都知道如何解决这个问题? 我需要一个独立处理正数和/或负数数据的解决方案。

感谢您的帮助!

【问题讨论】:

    标签: r shiny colors label plotly


    【解决方案1】:

    您必须确保您的label 是一个包含两个级别的factor

    因此,以下行将很好地呈现第二个图:

    set.seed(1)
    ## make sure that label is a factor containing both levels
    ## even if there is just one level in the data
    d2 <- data.frame(category = as.factor(seq(10)), diff = runif(10, min=20, max=50)) %>% 
      mutate(label = factor(ifelse(diff <= 0, "green", "red"), c("green", "red"))) 
    
    d2 %>% 
      plot_ly(x=~diff, y=~category, type = 'bar', orientation = 'h', 
              color = ~label, colors = c("#009C48", "#E61414")) 
    

    【讨论】:

      猜你喜欢
      • 2012-10-20
      • 1970-01-01
      • 2017-04-09
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 2014-05-04
      • 2023-01-31
      • 2013-08-01
      相关资源
      最近更新 更多