Home > Net >  How to plot R Plotly bar chart with negative numbers
How to plot R Plotly bar chart with negative numbers

Time:04-08

I am looking to prepare an R Plotly horizontal bar chart. The chart values contain both negative and positive numbers, which I expect to plot similar to the ggplot example below (‘ggplot 1’). However, some of the colours/values are not visible in the Plotly chart (‘plotly 2’), not by their assigned colours anyways. The red of metric 1, for example, does not show, though it can be seen to be present by hovering the cursor over the bar in the chart.

I can get all the colours to show if the values are all positive (‘plotly 1’), however this isn’t accurate with the real data that I have. Is there something I need to do to make ‘plotly 2’ look like ‘ggplot 1’?

I am not looking for a ggplotly wrapper solution, and I am not looking to introduce a new hard-coded trace for each metric as the number of metrics in the production data may vary. Thanks in advance.

library(tidyverse)
library(plotly)

group_color_df <- tibble(
  group       = 'group_1'
  , metric    = paste0('metric_', 1:9)
  , value_wt_negs = c(-0.9, 0.5, -0.5, 0.6, -0.1, 0.1, 0.7, 0.1, 0.1)
  , value     = c(0.9, 0.5, 0.5, 0.6, 0.1, 0.1, 0.7, 0.1, 0.1)
  , met_color = c('#ff0000','#ddff00','#1eff00','#a800fc','#00eaff','#0400ff','#ff6f00','#ff00ff','#f5f3f0')
  , real_col  = c('red', 'yellow', 'green', 'purple', 'lightblue', 'blue', 'orange', 'pink', 'grey'
  )
)


group_color_df %>% 
  ggplot(aes(x = group, y = value_wt_negs, fill = metric))  
  geom_col(width = 0.4)  
  coord_flip()  
  theme_minimal()  
  scale_fill_manual(values = group_color_df$met_color)  
  ggtitle('ggplot 1')


group_color_df %>%
  plot_ly(
    x             = ~value
    , y           = ~group
    , type        = 'bar'
    , orientation = 'h'
    , color       = ~metric
    , colors      = ~met_color
  ) %>%
  layout(
    bargap = 0.8
    , barmode = 'stack'
    , title = 'plotly 1'
  )

group_color_df %>%
  plot_ly(
    x             = ~value_wt_negs
    , y           = ~group
    , type        = 'bar'
    , orientation = 'h'
    , color       = ~metric
    , colors      = ~met_color
  ) %>%
  layout(
    bargap = 0.8
    , barmode = 'stack'
    , title = 'plotly 2'
  )

CodePudding user response:

You should use barmode = 'relative' in your layout. You can use the following code:

library(tidyverse)
library(plotly)

group_color_df %>%
  plot_ly(
    x             = ~value_wt_negs
    , y           = ~group
    , type        = 'bar'
    , orientation = 'h'
    , color       = ~metric
    , colors      = ~met_color
  ) %>%
  layout(
    bargap = 0.8
    , barmode = 'relative'
    , title = 'plotly 2'
  )

Output:

enter image description here

As you can see, all the colors are shown in the plot.

  • Related