简体   繁体   English

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

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

Here is my code that I am using:这是我正在使用的代码:

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))

Output is:输出是:

在此处输入图片说明

In the above visualization, the line starts from mid December and ends in mid February.在上面的可视化中,这条线从 12 月中旬开始,到 2 月中旬结束。 Is it possible to start the line from extreme left and ends in extreme right so that it looks more continuous type?是否可以从最左边开始并在最右边结束,以便它看起来更连续?

I tried to play with the dates in DF and DF1 and it seems possible to achive what you are looking for by just moving DF1 to mid of the month 15th and moving DF to beginning of december, mid of january and end of february.我尝试使用 DF 和 DF1 中的日期,似乎可以通过将 DF1 移动到 15 日中旬并将 DF 移动到 12 月初、1 月中旬和 2 月底来实现您想要的。 Just used +-2 days at the beginning and the end for the lines to look nicer:只是在开头和结尾使用了 +-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)
)

在此处输入图片说明

If you want the labels to appear correctly (just took me a while to figure it out)如果您希望标签正确显示(我花了一段时间才弄明白)

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