在 R Highchart 中手动重新排序条形图
Manually reordering Bar Chart in R Highchart
我是 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 放在最后,将 Stacy 放在第一位。
有人对此有解决方案吗?
您可以通过按所需顺序设置因子水平并排列数据集来获得所需结果:
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))
一种简单的方法是使用 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))
我是 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 放在最后,将 Stacy 放在第一位。
有人对此有解决方案吗?
您可以通过按所需顺序设置因子水平并排列数据集来获得所需结果:
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))
一种简单的方法是使用 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))