ggplotly将多个时间序列绘制为带有dynamicTicks = T的条形图

时间:2018-10-03 18:54:56

标签: r ggplot2 bar-chart plotly

我想将多个时间序列绘制为plotly + ggplot2的条形图,但是在使用dynamicTicks = TRUE时遇到问题。与我要避免的另一数据集相比,一个数据集的条形宽度增加并散布在更大的时间范围内。

通过设置dynamicTicks = FALSE(示例中红色条的宽度)看起来是正确的,但是x轴标签在放大时消失了。

将x值更改为字符也会使宽度看起来正确,但是x轴的标签重叠并且不会继承任何逻辑。

如何将一个数据集的条形宽度设置为与另一个数据集相同,将x值保持为“日期”格式并使用dynamicTicks = TRUE

library(ggplot2)
library(plotly)
library(data.table)

## Data
data1 <- {data.table(
  time_stamp = seq.Date(as.Date("2018-01-01"), to = as.Date("2018-07-04"), by = 1),
  q = runif(185, 100, 5000), qall = sample(1:8, size = 185, T),
  col = sample(c("green", "lightgreen", "yellow"), 185,T)
)}
data2 <- {data.table(
  time_stamp = seq.Date(as.Date("2018-01-01"), to = as.Date("2018-07-01"), by = 7),
  q = runif(26, 100, 5000), qall = sample(1:8, size = 26, T)
)}


key <- highlight_key(data1, ~time_stamp)
maxY = max(data1$q)
p <- ggplot() +
  geom_col(data = data2, aes(x = (time_stamp), y = maxY, 
                         text = paste("I AM TOO WIDE: <br>Date: ", (time_stamp))), 
           width = 1, fill = "red", alpha=0.4) +
  geom_col(data = key, aes(x = (time_stamp), y = q),
           width = 1, color="gray", fill = data1$col) +
  theme(text = element_text(size=9), axis.text.x = element_text(angle=0, hjust=1))

## Too Wide red bars + Correct x labels
dp <- ggplotly(p, source = "src", dynamicTicks = T, 
               tooltip = c("text")) %>% 
  highlight(off="plotly_doubleclick", color = "blue", opacityDim = 0.8); 
dp

左边的图像有dynamicTicks = T和太宽的红条,右边的图像有dynamicTicks = FALSE,校正了红条,但没有真正的xAxis逻辑。

我试图设置那些选项没有成功:

# plotly_json(dp)

dp$x$data[[1]]$width = rep(1, length(dp$x$data[[1]]$width))
dp
dp$x$data[[1]]$width = s$time_stamp
dp
dp$x$data[[1]]$marker$line$width = 1
dp

1 个答案:

答案 0 :(得分:1)

使用dynamicTicks = TRUEggplotly根据单个迹线的观察之间的间隔调整列宽。对于data2,这是7天,而对于data1,则只有1天。

解决此问题的一种方法是在data2中添加观察值;例如,将data2替换为以下内容:

library(tidyverse)
data3 = 
  data2 %>%
  mutate(maxY = max(data1$q)) %>% 
  complete(time_stamp = seq.Date(from = min(data2$time_stamp),
                                 to = max(data2$time_stamp),
                                 by = 1)
  ) %>% 
  replace_na(list(maxY=0))

请注意,您需要最后一个replace_na,因为y=0不会渲染带有plotly的列,而NA将会被删除,您将再次获得较宽的列