繁体   English   中英

如何在 R 中的条形线 Plotly 对象中绘制一条连续线?

[英]How could I plot a continuous line in bar- line Plotly object in R?

这是我正在使用的代码:

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 月中旬结束。 是否可以从最左边开始并在最右边结束,以便它看起来更连续?

我尝试使用 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"))
  )) 

在此处输入图片说明

暂无
暂无

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

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