How to Change Order of Stacked-Bar Chart in Plotly to Specific Column?

Hi,

I am currently struggling with creating a specific stacked bar-chart plot for my research. I have created a dummy dataframe to showcase my issue.

Goal:

The dataframe has four columns duration, chapter, unit, and pattern. It contains data about the structure of online courses (e.g. Udacity). The pattern column describes what types of media (i.e. v = video, t = text, e = exercise) are used and in what order. The duration column gives an estimate for the completion time.

To visualize these findings and compare the structure of different chapters I wrote a function in R that creates a stacked bar-chart where the duration is on the x-axis and the chapters are on the y-axis. Each unit is given a color based on its media-composition and is as "wide" as its duration.

Problem:

Unfortunately I am not able to make the order of the stacked bar-charts for the chapters be in the order of the units that are included inside them (I also tried changing the unit column to c(1, 2, 3, 1, 2) which did not work).

My function arranges the units in the wrong order. It arranges them alphabetically based on the pattern, which I do not want. It needs to be arranged by the unit column. Otherwise the plot will not tell the story I envision.

I hope someone can help me.

Code

library(plotly)
library(dplyr)
library(ggplot2)

df <- data.frame(
  duration = c(60, 120, 200, 90, 80),
  chapter = c("1", "1", "1", "2", "2"),
  unit = c("1.1", "1.2", "1.3", "2.1",  "2.2"),
  pattern = c("v", "t", "v", "vt", "ve")
)

plot_stacked_bar_chart <- function(df) {
  df %>%
    plot_ly(
      x = ~duration,
      y = ~chapter,
      color = ~pattern,
      type = "bar",
      orientation = "h"
    ) %>%
    layout(
      barmode = "stack",
      xaxis = list(
        categoryorder = "array",
        categoryarray = ~unit
      )
    )
}

plot_stacked_bar_chart(df)

(Please note that I did not include a reprex as plotly seems to be incompatible with it)

Output

(Note how the observations are sorted alphabetically based on the pattern, and not on the unit like I tried with the layout option for xaxis)

Best regards,
Michael

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.