0

我对使用 highcharterhc_add_series函数有点困惑。

我正在尝试创建一个需要指定 x 轴和 y 轴的图,其中 x 轴是连续的。我有一个数据框,例如:

df_plot <- cbind(
  seq(0, 1, by = 0.1),
  sample(seq(from = 100, to = 300, by = 10), size = 11, replace = TRUE),
  sample(seq(from = 1, to = 100, by = 9), size = 11, replace = TRUE),
  sample(seq(from = 50, to = 60, by = 2), size = 11, replace = TRUE),
  sample(seq(from = 100, to = 130, by = 1), size = 1, replace = TRUE)
) %>% 
  as.data.frame()

names(df_plot) <- c("x", "a", "b", "c", "d")

我看到了这个有效的例子

highchart() %>%
    hc_add_series(data = purrr::map(4:8, function(x) list(x, x)), color = "blue")

所以我尝试了:

df_plot1 <- Map(cbind, split.default(df_plot[-1], names(df_plot)[-1]), x=df_plot[1])

highchart() %>%
  hc_add_series(data = df_plot1[[1]]) %>%
  hc_add_series(data = df_plot1[[2]], yAxis = 1) %>%
 hc_yAxis_multiples(
    list(lineWidth = 3, lineColor='#7cb5ec', title=list(text="First y-axis")),
    list(lineWidth = 3, lineColor="#434348", title=list(text="Second y-axis")))

但是,我在情节上得到“没有数据可显示”,所以我显然在某个地方出错了。

另外,我不能使用hchart函数,因为我需要有多个 y 轴

4

2 回答 2

2

阅读有关split.default它的文档后Divide into Groups and Reassemble,您需要访问要绘制的变量,例如df_plot1[[1]$a,如下所示:

library(highcharter)
df_plot <- cbind(
  seq(0, 1, by = 0.1),
  sample(seq(from = 100, to = 300, by = 10), size = 11, replace = TRUE),
  sample(seq(from = 1, to = 100, by = 9), size = 11, replace = TRUE),
  sample(seq(from = 50, to = 60, by = 2), size = 11, replace = TRUE),
  sample(seq(from = 100, to = 130, by = 1), size = 1, replace = TRUE)
) %>% as.data.frame()

names(df_plot) <- c("x", "a", "b", "c", "d")
df_plot1 <- Map(cbind, split.default(df_plot[-1], names(df_plot)[-1]), x=df_plot[1])

highchart() %>%
  hc_xAxis(categories = df_plot1[[1]]$x) %>%
  hc_add_series(data = df_plot1[[1]]$a) %>%
  hc_add_series(data = df_plot1[[2]]$b, yAxis = 1) %>%
  hc_yAxis_multiples(
    list(lineWidth = 3, lineColor='#7cb5ec', title=list(text="First y-axis")),
    list(lineWidth = 3, lineColor="#434348", title=list(text="Second y-axis")))

在此处输入图像描述

于 2017-08-29T07:24:19.820 回答
1

不知道这是否可以帮助你,

library(tidyr)
df_plot2 <- gather(df_plot, group, y, -x)

hchart(df_plot2, "line", hcaes(x, y, group = group)) 

hchart(df_plot2, "line", hcaes(x, y, group = group), yAxis = 0:3) %>% 
  hc_yAxis_multiples(
    list(lineWidth = 3, title=list(text="First y-axis")),
    list(lineWidth = 3, title=list(text="Second y-axis")),
    list(lineWidth = 3, title=list(text="3rd y-axis")),
    list(lineWidth = 3, title=list(text="4th y-axis"))
    )
于 2017-08-31T16:47:41.077 回答