highcharts 在R Highchart中手动重新排序条形图

00jrzges  于 2022-11-11  发布在  Highcharts
关注(0)|答案(2)|浏览(214)

我是highcharter的新手,我尝试手动重新排序条形图的类别,但似乎找不到一个即时的解决方案。我尝试使用fct_relevel重新排序,但它不起作用
我的代码看起来像这样:

library(highcharter)
library(tidyverse)

df <- data.frame(x= rep(c("john", "Luke", "Tom", "Sarah", "Laura", "Stacy"), each = 2), 
                 y = round(runif(12, min=0, max=100)),
                 z = rep(c(2020, 2021), each = 6)
                 )

df %>% hchart("bar", hcaes(x = x, y = y, group = z))

enter image description here
基本上,我希望能够手动设置轴类别的顺序,并根据自己的喜好重新定位它们,例如,将Luke放在最后,将斯泰西放在最前面。
有人能解决这个问题吗?

gr8qqesn

gr8qqesn1#

一个简单的方法是使用hc_axis来定义类别的顺序。

library(highcharter)
library(tidyverse)

df %>%
  hchart("bar", hcaes(x = x, y = y, group = z)) %>%
  hc_xAxis(categories = list("Stacy", "john", "Tom", "Sarah", "Laura", "Luke"))

输出

数据类型

set.seed(123)

df <-
  data.frame(x = rep(c(
    "john", "Luke", "Tom", "Sarah", "Laura", "Stacy"
  ), each = 2),
  y = round(runif(12, min = 0, max = 100)),
  z = rep(c(2020, 2021), 6))
mm5n2pyu

mm5n2pyu2#

您可以通过按所需顺序设置因子水平并排列数据集来获得所需结果:

library(highcharter)
library(tidyverse)

set.seed(123)

df <- data.frame(x= rep(c("john", "Luke", "Tom", "Sarah", "Laura", "Stacy"), each = 2), 
                 y = round(runif(12, min=0, max=100)),
                 z = rep(c(2020, 2021), 6)
)

df %>% 
  mutate(z = as.character(z),
         x = fct_relevel(x, "Luke", after = 0),
          x = fct_relevel(x, "Stacy", after = Inf)) %>% 
  arrange(x) %>%
  hchart("bar", hcaes(x = x, y = y, group = z))

相关问题