繁体   English   中英

如何避免在 R 中绘制丢失的日期

[英]How to avoid plotting missing dates in R plotly

我需要绘制一个面积图,它包含财务数据,我正在使用 plotly 来这样做。 问题是,plotly 具有检测时间序列格式的功能,并且通过简单地将线性线扩展到下一个可用数据输入来绘制甚至丢失的日期。 是否可以禁用此功能并仅绘制可用数据的时间序列?

library(plotly)

    Datetime <- c(
      "2016-01-05 00:00:00",
      "2016-01-06 00:00:00",
      "2016-01-07 00:00:00",
      "2016-01-08 00:00:00",
      "2016-01-11 00:00:00",
      "2016-01-12 00:00:00",
      "2016-01-13 00:00:00",
      "2016-01-14 00:00:00",
      "2016-01-15 00:00:00",
      "2016-01-18 00:00:00",
      "2016-01-19 00:00:00",
      "2016-01-20 00:00:00",
      "2016-01-21 00:00:00",
      "2016-01-22 00:00:00",
      "2016-01-25 00:00:00",
      "2016-01-26 00:00:00",
      "2016-01-27 00:00:00",
      "2016-01-28 00:00:00",
      "2016-01-29 00:00:00",
      "2016-02-01 00:00:00")
plotdata <- c(93763,110023,134873,138780,117038,117890,120025,140715,48567,87592,
              115852,145189,162258,121456,93643,128475,119310,105771,134946,90386)

volume_data <- data.frame(Datetime, plotdata)
plot_ly(volume_data, x = Datetime, y = plotdata, type = "bar")

这是一个基本的样本数据,如果你执行这个,你会注意到图中有空格。 虽然在我的执行中,我使用了面积图,但我已经用条形图呈现了一个示例数据,以便更容易注意到空白区域。 我知道 plotly 将 x 轴数据识别为时间序列并自动完成缺失的数据。 是否可以禁用此功能并仅绘制数据可用的日期和时间?

我找到了一个更简单的问题解决方案,并认为我会将其作为答案发布,这可能对其他人也有帮助。 如果你在布局中添加一个参数,它就会完美地工作

p <- plot_ly(volume_data, x = Datetime, y = plotdata, type = "bar")
p <- layout(p, xaxis = list(type = "category"))

这是一个可以为您提供所需的替代方案。

p <- plot_ly(
  x = c("Jan 5", "March 5", "April 5"),
  y = c(20, 14, 23),
  name = "SF Zoo",
  type = "bar")
p %>% layout(xaxis = list(title="Date"), yaxis = list(title="Volume Data"))

您只需要在绘图之前转换您的日期时间列(如 Jan 5, March 5 ... 格式)

在此处输入图片说明

现在似乎有一个选项可以在 plotly 中设置 rangebreaks: https ://plotly.com/r/time-series/

以下代码来自他们的网站。

library(plotly)

df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
fig <- plot_ly(
  type = "scatter",
  x = as.Date(df$Date, format= "%Y-%m-%d"), 
  y = df$AAPL.High,
  name = 'AAPL High',
  mode = "markers",
)
fig <- fig %>%
  layout(
    title = "Time Series with Custom Date-Time Format",
    xaxis = list(
      type = "date",
      range=c('2015-12-01', '2016-01-15'),
      rangebreaks = list( 
        list(bounds=c("sat", "mon")),
        list(values=c("2015-12-25", "2016-01-01"))
      )
    )
  )
fig

暂无
暂无

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

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