dpel
dpel

Reputation: 2143

Colour plotly bar chart with error bars by group

Using this code:

data.frame(Group = LETTERS[1:6],
              Value = c(10,20,30,40,50,60),
              Shade = c("A","A","B","B","C","C"),
              UCI = c(1,2,3,4,5,6),
              LCI = c(1,2,3,4,5,6)) |> 
 plot_ly(x =~Group, 
      y=~Value, 
      color = ~Shade, 
      type = 'bar',
      error_y=~list(type="data",
                    symmetric = FALSE,
                    array=UCI, 
                    arrayminus = LCI))

I can create a plotly bar chart with error bars coloured by a vector enter image description here

However if I use some other strings to define my colours the error bars do not correspond to the data

    data.frame(Group = LETTERS[1:6],
              Value = c(10,20,30,40,50,60),
              Shade = c("similar","similar","higher","higher","lower","lower"),
              UCI = c(1,2,3,4,5,6),
              LCI = c(1,2,3,4,5,6)) |> 
   plot_ly(x =~Group, 
      y=~Value, 
      color = ~Shade, 
      type = 'bar',
      error_y=~list(type="data",
                    symmetric = FALSE,
                    array=UCI, 
                    arrayminus = LCI))      

enter image description here

Note the tool tips indicates that the error bars are now +/- 1 not 3 on column C.

Could someone explain what is happening here and how to solve it?

Upvotes: 1

Views: 63

Answers (1)

asd-tm
asd-tm

Reputation: 5263

I guess you might need an ordered factor as the groups (Shades) are ordered alphabetically if presented as vector:

data.frame(Group = LETTERS[1:6],
           Value = c(10,20,30,40,50,60),
           Shade = factor(c("similar","similar","higher","higher","lower","lower"), 
                          ordered=T, levels = c("lower","higher","similar")),
           UCI = c(1,2,3,4,5,6),
           LCI = c(1,2,3,4,5,6)) |> 
  plot_ly(x =~Group, 
          y=~Value, 
          color = ~Shade, 
          type = 'bar',
          error_y=~list(type="data",
                        symmetric = FALSE,
                        array=UCI, 
                        arrayminus = LCI))      

or workaround this sorting by adding prefixes:

data.frame(Group = LETTERS[1:6],
           Value = c(10,20,30,40,50,60),
           Shade = c("A. similar","A. similar","B. higher","B. higher","C. lower","C. lower"),
           UCI = c(1,2,3,4,5,6),
           LCI = c(1,2,3,4,5,6)) |> 
  plot_ly(x =~Group, 
          y=~Value, 
          color = ~Shade, 
          type = 'bar',
          error_y=~list(type="data",
                        symmetric = FALSE,
                        array=UCI, 
                        arrayminus = LCI))  

enter image description here

Upvotes: 2

Related Questions