R语言 如何更改y轴格式,同时有百分比更改选项?

ddarikpa  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(113)

我有两个数据集:data和data2。两者都有两列(一列有日期,另一列有值)。
数据集:

data <- structure(list(DATA = structure(c(19327, 19328, 19331, 19332, 
                                         19333, 19334, 19335, 19338, 19339, 19340, 19341, 19342, 19345, 
                                         19346, 19347, 19348, 19349), class = "Date"), AUM = c(32962594L, 
                                                                                               33213220L, 33278745L, 33482196L, 33591402L, 33591402L, 33660796L, 
                                                                                               33810382L, 34172853L, 34264748L, 34032274L, 34216610L, 34416588L, 
                                                                                               34462226L, 35308681L, 35429483L, 35456650L)), row.names = c(NA, 
                                                                                                                                                           -17L), class = "data.frame")

data2 <- structure(list(DATA = structure(c(19327, 19328, 19331, 19332, 
                                          19333, 19334, 19335, 19338, 19339, 19340, 19341, 19342, 19345, 
                                          19346, 19347, 19348, 19349), class = "Date"), CUM_SUM = c(0L, 
                                                                                                    173080L, 318158L, 504538L, 607304L, 607304L, 771404L, 916984L, 
                                                                                                    1153354L, 1292314L, 1381434L, 1708534L, 1937284L, 2035272L, 2817863L, 
                                                                                                    3046949L, 3046949L)), row.names = c(NA, -17L), class = "data.frame")

我希望显示一个图形,该图形不仅显示值的级数,而且对于每个点,还指示相对于第一个值的百分比变化。我还希望y_axis是点的值,而不是百分比变化。我现在的图形显示一个系列(数据)的百分比变化,但y_axis不是所需的格式。我希望看到的不是百分比变化,而是值。
这是我的图形代码:

highchart() %>%
  hc_yAxis_multiples(list(title = list(text = "data"), opposite = FALSE),
                     list(showLastLabel = FALSE, opposite = TRUE, title = list(text = "data2"))) %>%
  hc_add_series(name = "data", yAxis = 0, id = "data_line", data = data, hcaes(x = DATA, y = AUM), type = 'line', compare = 'percent') %>%
  hc_add_series(name = 'data2', yAxis = 1, id = 'data2_line', data = data2, hcaes(x = DATA, y = CUM_SUM), type = 'line') %>%
  hc_xAxis(type = "datetime") %>% 
  hc_plotOptions(column = list(dataLabels = list(enabled = F),enableMouseTracking = T)) %>%
  hc_chart(zoomType = 'xy') %>%
  hc_colors(c("#336600","#990000")) %>%
  hc_tooltip(pointFormat = '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change} %)<br/>',
             split = TRUE, crosshairs = TRUE) %>%
  hc_exporting(enabled = TRUE)

这是代码生成的图表:

如您所见,左侧y_axis的格式不是所需的格式。

mwkjh3gx

mwkjh3gx1#

更新:自定义格式值和拆分工具提示

在注解中,我写道您可以将JS中的y声明替换为y = Highcharts.numberFormatter(this.y, 0, '.', ' ');
这里有几处错误。首先,它是Highcharts.numberFormat〈-(最后没有ter)。很抱歉。如果是这样的话,我会添加另一个评论。然而,这导致了一些其他的问题,我没有考虑到这一点不太好的信息。所以为了纠正这一点,并解决您关于拆分工具提示的其他评论,我添加了以下信息。
这是我最初提供的图,没有拆分工具提示,但带有 * 格式的值。我更改了3:ydelta,以及如何在字符串tooltip中调用y
delta中,我将y更改为this.y(紧跟在y = Highcharts...后面的行是创建delta的行)。
tooltip中,我从${y}中删除了toFixed()

#----------------- with modified number formatting ------------------
highchart() %>%  # three y-axes with min/max scaling
  hc_add_series(data, type = "line", name = "Data Values ($)",
                compare = F, id = 'dv',
                hcaes(x = DATA, y = AUM)) %>% 
  hc_add_series(data, type = "line", name = "Data Values ($)",
                compare = 'percent', linkedTo = 'dv', visible = F, # <-- linked & invisible!
                hcaes(x = DATA, y = AUM)) %>% 
  hc_add_series(data2, type = "line", name = "Data2", compare = F,
                hcaes(x = DATA, y = CUM_SUM), yAxis = 1) %>% 
  hc_yAxis_multiples(list(title = list(text = "Data Values ($)"), opposite = F),
                     list(title = list(text = "Data2"), opposite = T)) %>% 
  hc_chart(zoomType = 'xy') %>%
  hc_colors(c("#336600","#336600","#990000")) %>% # added first color 2 times to account for invisible axes
  hc_tooltip(
    formatter = htmlwidgets::JS(
      "function(tooltip) {
          /* collect name, x (and format it), y, color, compare value, and % difference */
      nm = this.series.name;
      if(nm == 'Data2') {    /* use standard tooltip for data2 */
       return tooltip.defaultFormatter.call(this, tooltip);
      }
      xform = Highcharts.dateFormat('%B %e, %Y', this.x);        /* collect/format date */
      compVal = this.series.linkedSeries[0].dataModify.compareValue; /* 1st val in view */
      col = this.color;                                      /* set color and y to vars */
      y = Highcharts.numberFormat(this.y, 0, '.', ' ');    /*   <<---- I'm new!!   */
      delta = (this.y - compVal)/compVal * 100; /* compute the comparison value as HC does */   
      tooltip = `<span>${xform}<br><hr><b><span style='color:${col};'>`; /* create tooltip */
      tooltip += `● ${nm}:</span></b> ${y} (${delta.toFixed(2)}%)</span>`;
      return tooltip; /* send back new tooltip */
      }")) %>% 
  hc_exporting(enabled = TRUE) %>% 
  hc_xAxis(type = "datetime")

拆分工具提示

如果按照JS操作,当工具提示没有拆分时,会看到返回了一个字符串,这个字符串是使用多个变量创建的,前面加了this
拆分工具提示时,每个绘制的轨迹都在this.points中有一个索引。此外,需要为拆分中的每个项返回一个字符串。在图形中,有1个x轴项和2个y轴项,因此需要返回3个字符串。

#----------------- with modified number formatting &&& SPLIT tooltips ------------------
highchart() %>%  # three y-axes with min/max scaling
  hc_add_series(data, type = "line", name = "Data Values ($)",
                compare = F, id = 'dv',
                hcaes(x = DATA, y = AUM)) %>% 
  hc_add_series(data, type = "line", name = "Data Values ($)",
                compare = 'percent', linkedTo = 'dv', visible = F, # <-- linked & invisible!
                hcaes(x = DATA, y = AUM)) %>% 
  hc_add_series(data2, type = "line", name = "Data2", compare = F,
                hcaes(x = DATA, y = CUM_SUM), yAxis = 1) %>% 
  hc_yAxis_multiples(list(title = list(text = "Data Values ($)"), opposite = F),
                     list(title = list(text = "Data2"), opposite = T)) %>% 
  hc_chart(zoomType = 'xy') %>%
  hc_colors(c("#336600","#336600","#990000")) %>% # added first color 2 times to account for invisible axes
  hc_tooltip(split = 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 */
        if(nm != 'Data2'){
          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 */
        } else {     
          adder = '';                         /* if data2, there are no calculations to add */
        }
        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) %>% 
  hc_xAxis(type = "datetime")

如果您的数字格式选择与我指定的不一样,下面是参数:

Highcharts.numberFormat(value, decimalPlaces, decimalPoint, thousandsSeparator);
最初提供:

当您将名为data的序列设置在左侧时,您告诉Highcharts制作y轴百分比。但是,即使您操纵这些轴以显示实际股票值,Highcharts仍将在x轴上绘制日期,在y轴上绘制百分比。
%补偿值绘制线将与$y轴不匹配。
我试着想一种方法来更好地表达我的意思,以及为什么你不能做你正在尝试做的事情...我采取了股票价值,并创建了基于几个范围的模拟比较值(以模拟各种缩放设置和compare如何变化)。
你会看到股票价格可能会上升,但这并不意味着compare的值也会上升,你还会看到这些值会根据你缩放的位置而变化,你必须无限地调整$轴的大小才能与%轴对齐。
下面是制作情节的代码,我提到的情节概述了这个问题。

library(highcharter)
library(quantmod)

# get stock info
goo <- getSymbols("GOOG", auto.assign = F)

# frame data for building comparison values
df1 <- data.frame(dt = seq.Date(from = as.Date("2020-01-01"),
                                length.out = 300, by = "day"),
                  goo$GOOG.Open[1001:1300]) %>% 
  setNames(c("dt", "val"))

# four sets of comparison values
df1$fromO <- c(NA, ((df1$val - df1[1, ]$val)/df1[1, ]$val)[-1])
df1$from100 <- c(rep(NA, 100), ((df1$val - df1[100, ]$val)/df1[100, ]$val)[101:300])
df1$from200 <- c(rep(NA, 200), ((df1$val - df1[200, ]$val)/df1[200, ]$val)[201:300])
df1$btw150250 <- c(rep(NA, 150), ((df1$val - df1[150, ]$val)/df1[150, ]$val)[151:250], rep(NA, 50))

df1[, 3:6] <- df1[,3:6] * 100   # get % value 

# visualize the issue with plotting comp value but labeling it with the $
highchart() %>% 
  hc_add_series(df1, type = "line", name = "Original Data",
                hcaes(x = dt, y = val)) %>% 
  hc_add_series(df1, type = "line", name = "100-300 Days",
                hcaes(x = dt, y = from100), yAxis = 1) %>% 
  hc_add_series(df1, type = "line", name = "200-300 Days",
                hcaes(x = dt, y = from200), yAxis = 1) %>% 
  hc_add_series(df1, type = "line", name = "Between 150-250 Days",
                hcaes(x = dt, y = btw150250), yAxis = 1) %>% 
  hc_xAxis(type = "datetime") %>% 
  hc_yAxis_multiples(list(opposite = F, title = list(text = "Stock Value ($)")),
                     list(opposite = T, title = list(text = "Comparative (%)")))

你可以用日期和 * 值 * 来表示比较值,也可以用 * 工具提示 * 或标签来表示比较值,或者用相反的y轴来表示数据和比较值,但是如果你这样做,data2就不适用了。
为什么data2不能这样做呢?
一张图片可以更快地回答这个问题:
如果有2个轴,则三个轴中的一个基本上是一条平线。
如果你有3个轴,你可能可以对齐他们最初...检查出来:

# new range for values axes (align to compare and data2)
low <- min(data$AUM)
high <- max(data$AUM)

# determine 'equivalent to 10' to match scale, using 0-7.57 as old scale
newH <- round(10 * (high - low)/7.57 + low, 0)
newI <- round((newH - low)/5, 0) # new interval of axes

highchart() %>%  # three y-axes with min/max scaling
  hc_add_series(data, type = "line", name = "Data Values ($)",
                compare = F,
                hcaes(x = DATA, y = AUM)) %>% 
  hc_add_series(data, type = "line", name = "Date Compare (%)",
                compare = "percent", yAxis = 1,
                hcaes(x = DATA, y = AUM)) %>% 
  hc_add_series(data2, type = "line", name = "Data2", compare = F,
                hcaes(x = DATA, y = CUM_SUM), yAxis = 2) %>% 
  hc_yAxis_multiples(list(opposite = F, #min = low, max = newH, tickInterval = newI,
                          tickInterval = newI, min = low,
                          breaks = list(breakSize = 1,
                                        from = 0, to = low),
                          title = list(text = "Value ($)")),
                     list(opposite = T, min = 0, max = 10, # used previous plot scale
                          title = list(text = "Compare (%)")),
                     list(opposite = F, min = 0, max = 4000000, # used prev plot scale
                          title = list(text = "Data2"))) %>% 
  hc_xAxis(type = "datetime")

这里有一个随机缩放...看到的价值观不再对齐。

在这里可以看到,compare系列的绘图与值轴上的值不对齐。

另一个想法

像前面的问答一样,我建议您使用工具提示来装饰和显示comp值,并绘制实际值。
这将使用您在图表中特别指定的数据和功能。但是,它会绘制值,隐藏compare线,并将复合线数据添加到值的工具提示中。
对于data2,我使用了默认的工具提示。

下面是绘制该图的代码。

highchart() %>%  # three y-axes with min/max scaling
  hc_add_series(data, type = "line", name = "Data Values ($)",
                compare = F, id = 'dv',
                hcaes(x = DATA, y = AUM)) %>% 
  hc_add_series(data, type = "line", name = "Data Values ($)",
                compare = 'percent', linkedTo = 'dv', visible = F, # <-- linked & invisible!
                hcaes(x = DATA, y = AUM)) %>% 
  hc_add_series(data2, type = "line", name = "Data2", compare = F,
                hcaes(x = DATA, y = CUM_SUM), yAxis = 1) %>% 
  hc_yAxis_multiples(list(title = list(text = "Data Values ($)"), opposite = F),
                     list(title = list(text = "Data2"), opposite = T)) %>% 
  hc_chart(zoomType = 'xy') %>%
  hc_colors(c("#336600","#336600","#990000")) %>% # added first color 2 times to account for invisible axes
  hc_tooltip(
    formatter = htmlwidgets::JS(
      "function(tooltip) {
          /* collect name, x (and format it), y, color, compare value, and % difference */
      nm = this.series.name;
      if(nm == 'Data2') {    /* use standard tooltip for data2 */
       return tooltip.defaultFormatter.call(this, tooltip);
      }
      xform = Highcharts.dateFormat('%B %e, %Y', this.x);        /* collect/format date */
      compVal = this.series.linkedSeries[0].dataModify.compareValue; /* 1st val in view */
      col = this.color; y = this.y;                          /* set color and y to vars */
      delta = (y - compVal)/compVal * 100;   /* compute the comparison value as HC does */   
      tooltip = `<span>${xform}<br><hr><b><span style='color:${col};'>`; /* create tooltip */
      tooltip += `● ${nm}:</span></b> ${y.toFixed(0)} (${delta.toFixed(2)}%)</span>`;
      return tooltip; /* send back new tooltip */
      }")) %>% 
  hc_exporting(enabled = TRUE)

相关问题