Billboarder.R,具有多个要绘制变量的分组折线图

问题描述 投票:1回答:1

我正在尝试映射我的桌子。它在具有一年中的星期(1-53)的x轴和具有一定百分比(0-100)的y轴上绘制。在此绘图中,我尝试绘制两行,一行用于变量“ Task”,另一行用于变量“ Area”。但是,由于x轴仅使用一年,因此我还希望每年都有一条新线。

我的数据如下:

head(dt.Ratio()[Week %in% c(52, 53, 1, 2, 3)])
       year Week  Area  Task
    1: 2019   52 63.68 28.39
    2: 2019   53  3.23  0.00
    3: 2020    1 58.58 25.43
    4: 2020    2 61.54 31.75
    5: 2020    3 52.33 27.10

和情节的完成是这样的:

billboarder() %>%
        bb_linechart(dt.Ratio(), show_point = TRUE, type = "area") %>%
        bb_x_axis(label = list(text = "Week", position = "outer-right"),
                  tick = list(culling = list(max = 1))) %>%
        bb_y_axis(label = list(text = "Ratio of hours clocked as task", position = "outer-right")) %>%
        bb_y_grid(show = TRUE) %>%
        bb_colors_manual(opacity = 0.25)

我做了很多尝试来使用bb_linechart中的映射变量,但找不到正确的映射。我可以使其适用于Area或Task,也可以不按年份分组,但是我还没有找到一种解决方案来包含所有4行(2019年和2020年,Task和Area变量)

r plot billboard.js
1个回答
1
投票

您好,您将需要转换一些数据。

第一个选项:使用日期

library(data.table)
library(billboarder)

dt <- fread(text = "year Week  Area  Task
2019   52 63.68 28.39
2020    1 58.58 25.43
2020    2 61.54 31.75
2020    3 52.33 27.10")

# Convert date
dt[, date := as.Date(paste(year, Week, 1, sep = "-"), format = "%Y-%U-%u")]

# Pivot data
dt <- melt(
  data = dt, 
  id.vars = "date",
  measure.vars = c("Area", "Task")
)

# Plot
billboarder() %>%
  bb_linechart(dt, bbaes(x = date, y = value, group = variable), show_point = TRUE, type = "area") %>%
  bb_x_axis(label = list(text = "Week", position = "outer-right"),
            tick = list(culling = list(max = 1))) %>%
  bb_y_axis(label = list(text = "Ratio of hours clocked as task", position = "outer-right")) %>%
  bb_y_grid(show = TRUE) %>%
  bb_colors_manual(opacity = 0.25)

enter image description here

第二个选项:将年和周连接为字符串

library(data.table)
library(billboarder)

dt <- fread(text = "year Week  Area  Task
2019   52 63.68 28.39
2020    1 58.58 25.43
2020    2 61.54 31.75
2020    3 52.33 27.10")

# Or just concatenate year and week
dt[, year_week := paste(year, Week, sep = "-")]

# Pivot data
dt <- melt(
  data = dt, 
  id.vars = "year_week",
  measure.vars = c("Area", "Task")
)

# Plot
billboarder() %>%
  bb_linechart(dt, bbaes(x = year_week, y = value, group = variable), show_point = TRUE, type = "area") %>%
  bb_x_axis(
    type = "category",
    label = list(text = "Week", position = "outer-right"),
    tick = list(culling = list(max = 1))
  ) %>%
  bb_y_axis(label = list(text = "Ratio of hours clocked as task", position = "outer-right")) %>%
  bb_y_grid(show = TRUE) %>%
  bb_colors_manual(opacity = 0.25)

您必须在type = "category"中使用bb_x_axis,结果有点不同:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.