How to sort an R Plotly grouped bar chart within groups?

Reproducible example:

library(data.table)
library(plotly)

df <- data.table(
  x = c(rep("positive", 4), rep("neutral", 4), rep("none", 4), rep("negative", 4)),
  y = rep(c("one", "two", "three", "four"), 4),
  percent = c(
    38.9, 33.3, 8.7, 19.1, 29.4, 29.6, 21.6, 19.4,
    37.4, 24.9, 16.6, 21.1, 27.8, 34.5, 14.4, 23.2
  )
)

# Sort rows based on 'percent' within each subgroup in 'y', preserving grouping in 'x'
df <- df[order(x, -percent)]

plot_ly(
  df, 
  x = ~percent,
  y = ~x,
  color = ~y,
  type = "bar",
  orientation = "h",
  hovertemplate = "Group: %{fullData.name} <br> Percent: %{x}% <extra></extra>",
  opacity = 0.9,
  hoverlabel = list(
    align = "left"
  )
) %>%
  layout(
    font = list(
      family = "Open Sans",
      size = 13
    ),
    xaxis = list(
      title = "", 
      showticklabels = TRUE
    ),
    yaxis = list(
      title = ""
    )
  )

This produces the following chart:

enter image description here

How do I sort the bars from highest to lowest (percentages) within each group? Is this possible at the R level? I tried specifying categoryorder and categoryarray parameters in layout but it doesn't seem to take effect? Thanks.


Solution 1:

So this is what I would do for a faceted solution which uses ggcharts library and bar_chart:

p <- ggcharts::bar_chart(
  df,
  y,
  percent,
  fill = x,
  facet = x,
)
p

Not exactly what you wanted

Solution 2:

Minimal solution based on Andrew Ingalls' solution and Dan Adams' suggestion in the comment:

library(ggcharts)
ggcharts::bar_chart(
    df,
    y,
    percent,
    fill = x,
    facet = x,
  ) |>
    plotly::ggplotly()

Also tested with plotly::renderPlotly().