简体   繁体   中英

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:

在此处输入图像描述

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.

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() .

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

不完全是你想要的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM