【问题标题】:How could I plot a continuous line in bar- line Plotly object in R?如何在 R 中的 bar-line Plotly 对象中绘制连续线?
【发布时间】:2021-02-21 02:17:12
【问题描述】:

这是我正在使用的代码:

library(dplyr)
library(plotly)

DF <- data.frame(
  Month = lubridate::as_date(c("2019-Dec-01", "2019-Dec-01","2020-Jan-01","2020-Jan-01","2020-Jan-01", "2020-Feb-01", "2020-Feb-01")),
  #Week = c(4L, 5L, 5L, 1L, 1L, 1L, 2L, 1L),
  Cat = c("A", "C", "A", "B", "C", "A", "C"),
  n = c(38L, 10L, 19L, 20L, 12L, 14L, 20L)
)

DF1 <- data.frame(
  Month = lubridate::as_date(c("2019-Dec-01", "2020-Jan-01", "2020-Feb-01")),
  n = c(20L, 41L, 9L)
)

plot_ly() %>%
  add_bars(data = DF, x = ~Month, y = ~n, type = 'bar', split = ~Cat) %>%
  add_lines(data = DF1, x = ~Month, y = ~n, color = I("black")) %>%
  layout(barmode = "stack", xaxis = list(type = 'date', tickformat = '%Y-%b', tickangle = 90, nticks = 4))

输出是:

在上面的可视化中,这条线从 12 月中旬开始,到 2 月中旬结束。 是否可以从最左边开始并在最右边结束,这样它看起来更连续的类型?

【问题讨论】:

    标签: r charts plotly line


    【解决方案1】:

    我尝试使用 DF 和 DF1 中的日期,只需将 DF1 移动到 15 月中旬并将 DF 移动到 12 月初、1 月中旬和 2 月底,似乎就可以实现您正在寻找的内容.只是在开头和结尾使用了 +-2 天,让线条看起来更好:

    DF <- data.frame(
      Month = lubridate::as_date(c("2019-Dec-15", "2019-Dec-15","2020-Jan-15","2020-Jan-15","2020-Jan-15", "2020-Feb-15", "2020-Feb-15")),
      #Week = c(4L, 5L, 5L, 1L, 1L, 1L, 2L, 1L),
      Cat = c("A", "C", "A", "B", "C", "A", "C"),
      n = c(38L, 10L, 19L, 20L, 12L, 14L, 20L)
    )
    
    DF1 <- data.frame(
      Month = lubridate::as_date(c("2019-Dec-03", "2020-Jan-15", "2020-Feb-27")),
      n = c(20L, 41L, 9L)
    )
    

    如果您希望标签正确显示(我花了一段时间才弄明白)

    plot_ly() %>%
      add_bars(data = DF, x = ~Month, y = ~n, type = 'bar', split = ~Cat) %>%
      add_lines(data = DF1, x = ~Month, y = ~n, color = I("black")) %>%
      layout(barmode = "stack", xaxis = list(
        type = 'date',
        ticktext = list("2019-Dec", "2020-Jan", "2020-Feb"), 
        tickvals = list(as.Date("2019-12-15"),as.Date("2020-01-15"),as.Date("2020-02-15"))
      )) 
    

    【讨论】:

    • 非常感谢您的回答。但我正在寻找更通用的解决方案,因为实际数据有数千行。
    • @PAULR67 如果您的所有日期都在当月 1 日,您只需将所有日期都添加 14 天。然后计算最小日期减去 12 或 13 天,最大日期加上 12 或 13 天。对于标签,您将使用 DF 中的所有不同日期作为 tickvals,然后将它们在第二个列表中转换为您想要的标签格式并将其提供给 ticktext
    猜你喜欢
    • 2017-09-24
    • 2018-02-19
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    相关资源
    最近更新 更多