简体   繁体   English

您如何使用 highcharter 包在 R 闪亮的折线图中提供多个系列而不对系列进行硬编码?

[英]How could you supply multiple series to a line chart in R shiny using highcharter package and without hardcoding the series?

I'm trying to create a line chart using highcharts package with a time series dataframe that is similar to this one:我正在尝试使用 highcharts 包创建一个折线图,其中包含与此类似的时间序列数据框:

reprexDF <- data.frame(category = c("apples","oranges","bananas","limes"),
                          month1 = c(5,8,10,2),
                          month2 = c(NA,7,2,3),
                          month3 = c(NA, NA, 10,2),
                          month4 = c(11,12,5,9)
                          )

I want each row to be a separate line on the line chart that shows the trend for each category across months, all plotted on the same chart.我希望每一行都是折线图上的一条单独的线,显示每个类别跨月的趋势,所有这些都绘制在同一个图表上。

I tried parsing each row into a list with:我尝试将每一行解析为一个列表:

reprexDF <- highcharter::list_parse2(reprexDf)

and then attempting to plot with:然后尝试绘制:

highchart() %>%
hc_plotOptions(line = list(marker = list(enabled = FALSE)))%>%
hc_add_series_list(reprexDF) 

but I'm still not being able to plot this data.但我仍然无法绘制这些数据。

I just really want to avoid having to hard code each series because the lists are supposed to be dynamic.我只是真的想避免对每个系列进行硬编码,因为列表应该是动态的。

Would first convert your data frame to long.首先将您的数据框转换为long。 Then you can group_by category and use list_parse2 to make lists by category.然后你可以group_by category 并使用list_parse2按类别制作列表。

For this plot, I made sure month was numeric on x-axis.对于这个图,我确保month是 x 轴上的数字。 I renamed category to name so it would show up in legend and labels.我将category重命名为name这样它就会显示在图例和标签中。 And added connectNulls in case you wanted to connect points across missing values ( NA ).并添加了connectNulls ,以防您想连接缺失值 ( NA ) 之间的点。

library(highcharter)
library(tidyverse)

reprexDF2 <- reprexDF %>%
  pivot_longer(cols = -category, names_to = "month", values_to = "value", names_pattern = "month(\\d)$") %>%
  group_by(category) %>%
  do(data = list_parse2(data.frame(as.numeric(.$month), .$value))) %>%
  ungroup() %>%
  rename(name = category)

highchart() %>%
  hc_plotOptions(series = list(connectNulls = TRUE), line = list(marker = list(enabled = FALSE)))%>%
  hc_add_series_list(reprexDF2)

带线的 highcharter

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

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