I am looking into the xaxis = list(type = multicategory)
layout option for a bar plot; not having the most luck.
Consider the following reprex
df <-
tibble::tibble(
cat1 = c("A", "B", "B", "C"),
cat2 = c("N/A", "5", "10", "5"),
value = 1:4
)
df |>
plotly::plot_ly(
x = ~ list(cat1, cat2),
y = ~ value,
color = ~ cat1, # Adds color to bars but breaks the plot
type = "bar"
) |>
plotly::layout(xaxis = list(type = "multicategory"))
When the color = ...
line is omitted, the plot acts as expected with nested categories (A:B then N/A,5,10).
However, by adding color only two bars (both have cat1 = B
) is shown and I have no idea why.
Any advice or indication where Iām going wrong would be appreciated.
Used the dash app to investigate the data.
Seems like using list results in data like [ "A", "N/A"]
for singley-observed groups and [ ["B", "B"], ["5", "10"]]
otherwise.
My initial use of rbind
meant the entire data was passed for every group and some value (such as "5"
) were put in the wrong cat1
(say, "A"
).
My solution is to add a trace for each category 1 / colour. That is,
plotly::plot_ly() |>
plotly::add_trace(
data = df[1, ],
x = ~ rbind(cat1, cat2),
y = ~ value,
color = ~ cat1, # Adds color to bars but breaks the plot
type = "bar"
) |>
plotly::add_trace(
data = df[2:3, ],
x = ~ rbind(cat1, cat2),
y = ~ value,
color = ~ cat1, # Adds color to bars but breaks the plot
type = "bar"
) |>
plotly::add_trace(
data = df[4, ],
x = ~ rbind(cat1, cat2),
y = ~ value,
color = ~ cat1, # Adds color to bars but breaks the plot
type = "bar"
) |>
plotly::layout(
xaxis = list(type = "multicategory")
)
I also installed library(dash)
so may have updated plotly, pretty sure both reprex were run on Plotly 4.10.1 (R package version)