繁体   English   中英

Highcharter 中的手动轴标签

[英]Manual axis labels in Highcharter

由于 highcharts 没有为人口金字塔提供 function,我通过为金字塔一侧的数据分配负值,使用 plot 列类型手动捏造了一个。 我面临的唯一问题是我无法弄清楚如何覆盖 x 轴标签,以便我可以将这些值显示为正值。

突出显示问题的人口金字塔图像

我还操纵了标题和副标题功能,这样我就可以为金字塔的两边创建标题。

这是一些示例代码:

data <- data.frame(x=as.factor(c(seq(1,10,1), seq(1,10,1))), 
                   y=sample(10:20, size=20, replace=T), 
                   group=c(rep(1,10), rep(2,10)))
data <- data %>%
  mutate(y = ifelse(group == 1, (-1)*y, y))

highchart() %>%
  hc_add_series(
    data,
    type = "bar",
    hcaes(
      x = x,
      y = y,
      group = group
    ), showInLegend = F) %>% 
  hc_plotOptions(bar = list(stacking = "normal")) %>% 
  hc_title(text = "Group 1", align= "center", x = -115, y=20, margin=0,
           style = list(fontSize="12px", color="#0d233a")) %>%
  hc_subtitle(text = "Group 2", align= "center", y=20, margin=0,
              x = 130, style = list(fontSize="12px", color="#2f7ed8"))

我的主要问题是如何手动覆盖 x 轴,以便可以为金字塔的左侧分配正轴标签。 此外,如果有人知道如何以编程方式使标题和副标题居中,使它们位于金字塔每一侧的中心,那就太好了。

我试图使 x 轴分类并使用“类别”选项分配标签,但不知何故显示 20 代替 0,我无法弄清楚为什么或如何修复它。

ylim <- plyr::round_any(max(abs(data$y), na.rm=T), 5)
highchart() %>%
  hc_add_series(
    data,
    type = "bar",
    hcaes(
      x = x,
      y = y,
      group = group
    ), showInLegend = F) %>% 
  hc_plotOptions(bar = list(stacking = "normal")) %>% 
  hc_title(text = "Group 1", align= "center", x = -115, y=20, margin=0,
           style = list(fontSize="12px", color="#0d233a")) %>%
  hc_subtitle(text = "Group 2", align= "center", y=20, margin=0,
              x = 130, style = list(fontSize="12px", color="#2f7ed8")) %>%
  hc_yAxis(type="category", categories = as.factor(c(rev(seq(0,ylim,5)),
                                                     seq(5,ylim,5))), tickInterval=5)

我将衷心感谢您的帮助。 我也对使用 highcharter 包生成人口金字塔的完全不同的方法持开放态度。

由于您在 x 轴上有值,Highcharts认为y 是 x,x 是 y。 (我花了一分钟才弄明白为什么它不我说话。)

在 R 代码中,您会看到对hc_yAxis()的调用。 formatter function 会将您的 x 轴标签调整为其绝对值。

highchart() %>%
  hc_add_series(data, type = "bar", hcaes(x = x, y = y, group = group), 
                showInLegend = F) %>% 
  hc_plotOptions(bar = list(stacking = "normal")) %>% 
                        # format the labels on the x-axis (y-axis per HC)
  hc_yAxis(labels = list(formatter = htmlwidgets::JS( 
    "function() {
        return Math.abs(this.value); /* all labels to absolute values */
    }"
  ))) %>% 
  hc_title(text = "Group 1", align = "center", x = -115, y = 20, margin = 0,
           style = list(fontSize = "12px", color = "#0d233a")) %>%
  hc_subtitle(text = "Group 2", align = "center", y = 20, margin = 0,
              x = 130, style = list(fontSize = "12px", color = "#2f7ed8"))

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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