代码之家  ›  专栏  ›  技术社区  ›  user63230

具有多个起点和终点的哑铃图

  •  1
  • user63230  · 技术社区  · 10 月前

    我有以下哑铃图,对于某些群体来说,它有多个起点和终点:

    library(tidyverse)
    df <- structure(list(company = c("A", "A", "A", "A", "B", "B", "C", 
                               "C", "D", "D", "E", "E", "F", "F", "G", "G", "H", "H", "I", "I", 
                               "J", "J", "J", "J"), variable = c("customers", "potential_customers", 
                                                                 "customers", "potential_customers", "customers", "potential_customers", 
                                                                 "customers", "potential_customers", "customers", "potential_customers", 
                                                                 "customers", "potential_customers", "customers", "potential_customers", 
                                                                 "customers", "potential_customers", "customers", "potential_customers", 
                                                                 "customers", "potential_customers", "customers", "potential_customers", 
                                                                 "customers", "potential_customers"), date = structure(c(19840, 
                                                                                                                         19957, 20023, 20223, 19811, 20149, 19773, 20202, 19806, 20135, 
                                                                                                                         19859, 20201, 19815, 19951, 19786, 20085, 19854, 19909, 19831, 
                                                                                                                         19977, 19823, 20089, 20123, 20223), class = "Date")), row.names = c(NA, 
                                                                                                                                                                                             -24L), class = "data.frame")
    df
    ggplot(df, aes(x = date, y = company)) +
      geom_line() +
      geom_point(aes(color = variable), size = 3) +
      theme(legend.position = "bottom")
    

    enter image description here

    添加差距的最简单方法是什么 A J 在这种情况下,以自动化的方式?谢谢

    1 回复  |  直到 10 月前
        1
  •  2
  •   stefan    10 月前

    在数据中添加一列,对观察结果进行分组 customer s和 potential_customer s.然后可以将此列映射到 group aes,类似于:

    library(tidyverse)
    df |>
      dplyr::mutate(
        group = row_number(),
        .by = c(company, variable)
      ) |>
      ggplot(aes(
        x = date, y = company,
        group = interaction(company, group)
      )) +
      geom_line() +
      geom_point(aes(color = variable), size = 3) +
      theme(legend.position = "bottom")