r - 如何在 x 轴上对每月日期进行排序?

标签 r r-highcharter

更新:使用@Kat的答案绘制图表

enter image description here

enter image description here

最初写道:

我有两个数据集:data 和 data2,都有四列。

数据集:

data <- structure(list(year = c(2022, 2022, 2022, 2022, 2022, 2022, 2022, 
                                2022, 2022, 2022, 2022, 2022), 
                       month = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 
                       AUM = c(32679911L, 32346742L, 34420603L, 34420603L, 37224840L, 36470615L, 36470615L, 36368089L, 33122740L, 35996741L, 36653126L, 36047829L),
                       DATA = structure(c(19023, 19051, 19082, 19111, 19143, 19173, 19202, 19235, 19265, 19296, 19326, 19356), 
                                        class = "Date")), 
                  row.names = c(NA, -12L), 
                  class = c("data.table", "data.frame"))

data2 <- structure(list(year = c(2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022),
                    month = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 
                    CUM_SUM = c(-297163L, -552969L, -1186800L, -1323710L, -778329L, -334843L, 96513L, 75763L, 874981L, 1100124L, 1009281L, 961152L),
                    DATA = structure(c(19023, 19051, 19082, 19111, 19143, 19173, 19202, 19235, 19265, 19296, 19326, 19356), class = "Date")), 
               row.names = c(NA, -12L), class = c("data.table", "data.frame"))

数据如下所示:

enter image description here

这是我的图表的代码:

# Line Plot:
highchart() %>%
  hc_add_series(name = "AUM", yAxis = 0, id = "aum_line", data = data, type = 'line', hcaes(x = DATA, y = AUM), events = list(
    legendItemClick = htmlwidgets::JS(
      "function(e) {
                      var shown = this.visible ? false : true;
                      this.update({visible: shown});
                      return false;
                    }"
    ))) %>%
  hc_add_series(name = "AUM",id = 'aum_line_percent', data = data, type = "line", hcaes(x = DATA, y = AUM),
                compare = 'percent', linkedTo = 'aum_line', visible = F) %>% # <-- linked & invisible!)  
  hc_add_series(name = 'Cumulative NP', yAxis = 1, id = 'pl_cum_line', data = data2, type = 'line', hcaes(x = DATA, y = CUM_SUM), events = list(
    legendItemClick = htmlwidgets::JS(
      "function(e) {
                      var shown = this.visible ? false : true;
                      this.update({visible: shown});
                      return false;
                    }"
    ))) %>%
  hc_add_series(name = "Cumulative NP",id = 'pl_cum_line_percent', data = data2, type = "line", hcaes(x = DATA, y = CUM_SUM),
                compare = 'percent', linkedTo = 'pl_cum_line', visible = F) %>% # <-- linked & invisible!) 
  hc_yAxis_multiples(list(title = list(text = "AUM", style = list(fontSize = "1.5em", color = '#607B8B' )), opposite = FALSE),
                     list(showLastLabel = FALSE, opposite = TRUE, title = list(text = "Cumulative NP", style = list(fontSize = "1.5em", color = '#CD8162')))) %>%
  hc_xAxis(type = "datetime") %>% 
  hc_plotOptions(column = list(dataLabels = list(enabled = F),enableMouseTracking = T)) %>%
  hc_chart(zoomType = 'xy') %>%
  hc_colors(c('#607B8B','#607B8B','#CD8162','#CD8162')) %>%
  hc_tooltip(split = T, crosshairs = T,
             formatter = htmlwidgets::JS(
               "function(tooltip) {
                        function pref(pts) {                     /* create y-axis tooltips with this function */
                        col = pts.color; y = pts.y; nm = pts.series.name;        /* collect color, y, name */
                        compVal = pts.series.linkedSeries[0].dataModify.compareValue;  /* 1st val in view */
                        delta = (y - compVal)/compVal * 100;   /* compute the comparison value as HC does */
                        adder = `(${delta.toFixed(2)}%)</span>`;   /* create remaining string for tooltip */
                        y = Highcharts.numberFormat(y, 0, '.', ' ');                 /* format y after calc */
                        return `<b><span style='color:${col};'>● ${nm}:</span></b> ${y} ` + adder;
                        }
                        xform = Highcharts.dateFormat('%B %e, %Y', this.x);        /* x-axis tooltip formatted */
                        ttd1 = pref(this.points[0]);                /* call function to create y-axis tooltips */
                        ttd2 = pref(this.points[1]);
                        return [xform, ttd1, ttd2];                                 /* send tooltip formatting */
                        }")
  ) %>%
  hc_exporting(enabled = TRUE)

看起来像这样:

enter image description here

我想做的是将 x_axis 标签移动到右侧。例如,图表上的最后一点是 12 月 22 日的值,看起来像是 1 月 23 日的值。因此,不应是 4 月 22 日、7 月 22 日、10 月 22 日和 1 月 23 日,而应该是 3 月 22 日、6 月 22 日、9 月22 日和 12 月 22 日。

最佳答案

在 R 代码中,您会注意到我添加了 hourdateTimeLabelFormats。这是因为当我解析该月最后一天的日期时,JS 会自动检测您的时区。当我将格式恢复为数字时,JS 会根据您的时区进行调整。这最终会有所不同。由于日期不再是 0000(午夜),Highcharts 假定您希望 x 轴上有时间。我已将日期格式设置为月份名称缩写年份

There are methods to start and finish in Greenwich time. The simplest is to adjust the epoch by your timezone. Since my timezone is likely different than yours, which is likely different from whoever looks at your final chart, I've kept it simple. If you are near where the date changes (I think near Hawaii? Between Hawaii and Japan?) It might be worth ensuring the dates start and end in UTC. (Being that far from Greenwich could cause your dates to be an entire day off.)

我已注释掉对 hc_xAxis 的原始调用,并添加了一个新调用。这利用了参数tickPositioner。 Highcharts 认为属于 x 轴上的标签的任何内容都会被收集。该函数获取这些日期并确定上个月的最后一天。最后,它将 x 轴的新标签发送回图表。

与我提供的其他答案一样,我在 JS 中添加了注释来确定发生了什么。但是,如果您有任何疑问或有任何错误/未经测试的内容,请告诉我。

highchart() %>%
  hc_add_series(name = "AUM", yAxis = 0, id = "aum_line", data = data, type = 'line', hcaes(x = DATA, y = AUM), events = list(
    legendItemClick = htmlwidgets::JS(
      "function(e) {
                      var shown = this.visible ? false : true;
                      this.update({visible: shown});
                      return false;
                    }"
    ))) %>%
  hc_add_series(name = "AUM",id = 'aum_line_percent', data = data, type = "line", hcaes(x = DATA, y = AUM),
                compare = 'percent', linkedTo = 'aum_line', visible = F) %>% # <-- linked & invisible!)  
  hc_add_series(name = 'Cumulative NP', yAxis = 1, id = 'pl_cum_line', data = data2, type = 'line', hcaes(x = DATA, y = CUM_SUM), events = list(
    legendItemClick = htmlwidgets::JS(
      "function(e) {
                      var shown = this.visible ? false : true;
                      this.update({visible: shown});
                      return false;
                    }"
    ))) %>%
  hc_add_series(name = "Cumulative NP",id = 'pl_cum_line_percent', data = data2, type = "line", hcaes(x = DATA, y = CUM_SUM),
                compare = 'percent', linkedTo = 'pl_cum_line', visible = F) %>% # <-- linked & invisible!) 
  hc_yAxis_multiples(list(title = list(text = "AUM", style = list(fontSize = "1.5em", color = '#607B8B' )), opposite = FALSE),
                     list(showLastLabel = FALSE, opposite = TRUE, title = list(text = "Cumulative NP", style = list(fontSize = "1.5em", color = '#CD8162')))) %>%
  # hc_xAxis(type = "datetime", showLastLabel = F) %>% 
  hc_xAxis(tickPositioner = htmlwidgets::JS(
    "function() {
        oticks = this.tickPositions;                  /* get the current tick labels */
        giveMe = [];
        for(i = 0; i < oticks.length; i++) {          /* get last day of the month for each data point */
            tht = new Date(oticks[i]);
            tellMe = new Date(tht.getFullYear(), tht.getMonth(), 0);
            giveMe.push(tellMe.getTime());            /* revert date format to proper format for HC */
        }
        return giveMe;                                /* send updated tick labels to chart */
    }"),
    type = "datetime", dateTimeLabelFormats = list(month = '%b %Y', hour = '%b %Y')) %>% 
  hc_plotOptions(column = list(dataLabels = list(enabled = F),enableMouseTracking = T)) %>%
  hc_chart(zoomType = 'xy') %>%
  hc_colors(c('#607B8B','#607B8B','#CD8162','#CD8162')) %>%
  hc_tooltip(split = T, crosshairs = T,
             formatter = htmlwidgets::JS(
               "function(tooltip) {
                    function pref(pts) {                     /* create y-axis tooltips with this function */
                        col = pts.color; y = pts.y; nm = pts.series.name;       /* collect color, y, name */
                        compVal = pts.series.linkedSeries[0].dataModify.compareValue;  /* 1st val in view */
                        delta = (y - compVal)/compVal * 100;   /* compute the comparison value as HC does */
                        adder = `(${delta.toFixed(2)}%)</span>`;   /* create remaining string for tooltip */
                        y = Highcharts.numberFormat(y, 0, '.', ' ');               /* format y after calc */
                        return `<b><span style='color:${col};'>● ${nm}:</span></b> ${y} ` + adder;
                    }
                    xform = Highcharts.dateFormat('%B %e, %Y', this.x);       /* x-axis tooltip formatted */
                    ttd1 = pref(this.points[0]);               /* call function to create y-axis tooltips */
                    ttd2 = pref(this.points[1]);
                    return [xform, ttd1, ttd2];                                /* send tooltip formatting */
                }")) %>%
  hc_exporting(enabled = TRUE)

enter image description here

enter image description here

enter image description here

enter image description here

关于r - 如何在 x 轴上对每月日期进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75061328/

相关文章:

R 神经网络包对于数百万条记录来说太慢

r - 使用自定义函数进行数据帧矢量过滤

"%>%"链内的引用隧道变量

r - 如何让 highcharter 代表预测对象?

r - 如何在 r highcharter 中的条形旁边显示标签?

r - 将函数应用于数据框的所有元素

r - 将散点图和折线图与 R 中的 highcharter 相结合

r - Highcharter R 对数轴自定义按钮

r - 为什么 R 多核只使用一个核心?