簡體   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