使用plotly r 的多折线图

SNT*_*SNT 2 r dataframe plotly r-plotly

我有一个数据框,我试图使用plotly作为多折线图来绘制它。下面是数据框的样子:

  Month_considered pct.x pct.y   pct
   <fct>            <dbl> <dbl> <dbl>
 1 Apr-17            79.0  18.4  2.61
 2 May-17            78.9  18.1  2.99
 3 Jun-17            77.9  18.7  3.42
 4 Jul-17            77.6  18.5  3.84
 5 Aug-17            78.0  18.3  3.70
 6 Sep-17            78.0  18.9  3.16
 7 Oct-17            77.6  18.9  3.49
 8 Nov-17            77.6  18.4  4.01
 9 Dec-17            78.5  18.0  3.46
10 Jan-18            79.3  18.4  2.31
11 2/1/18            78.9  19.6  1.48
Run Code Online (Sandbox Code Playgroud)

当我迭代绘制多条线时,下面是使用的代码。

colNames <- colnames(delta)
p <-
  plot_ly(
    atc_seg_master,
    x = ~ Month_considered,
    type = 'scatter',
    mode = 'line+markers',
    line = list(color = 'rgb(205, 12, 24)', width = 4)
  )

for (trace in colNames) {
  p <-
    p %>% plotly::add_trace(y = as.formula(paste0("~`", trace, "`")), name = trace)
}

p %>%
  layout(
    title = "Trend Over Time",
    xaxis = list(title = ""),
    yaxis = list (title = "Monthly Count of Products Sold")
  )
p
Run Code Online (Sandbox Code Playgroud)

这就是输出的样子 在此输入图像描述

我的问题是如何从图表中删除trace 0month_considered删除,即使它不在我循环添加行的列名中。

Mat*_*ill 5

看来您被两件事绊倒了:

  1. 当您最初定义p并包含datax参数时,会创建一条跟踪 -- trace 0。您可以定义绘图,而无需提供任何数据或 x 值,只需p <- plot_ly()与任何所需的布局功能一起使用即可开始。
  2. 当您循环遍历列名称时,您的 x 轴列Month_Considered是该集合的一部分。您可以通过使用setdiff()(基本 R 的一部分)创建一个包含所有列名称(除了Months_Considered

将这两件事放在一起,实现您想要的目标的一种方法(多种可能的方法)如下:

library(plotly)

df <- data.frame(Month_Considered = seq.Date(from = as.Date("2017-01-01"), by = "months", length.out = 12),
                 pct.x = seq(from = 70, to = 80, length.out = 12),
                 pct.y = seq(from = 30, to = 40, length.out = 12),
                 pct = seq(from = 10, to = 20, length.out = 12))


## Define a blank plot with the desired layout (don't add any traces yet)
p <- plot_ly()%>%
  layout(title = "Trend Over Time",
         xaxis = list(title = ""),
         yaxis = list (title = "Monthly Count of Products Sold") )

## Make sure our list of columns to add doesnt include the Month Considered
ToAdd <- setdiff(colnames(df),"Month_Considered")

## Add the traces one at a time
for(i in ToAdd){
  p <- p %>% add_trace(x = df[["Month_Considered"]], y = df[[i]], name = i,
                       type = 'scatter',
                       mode = 'line+markers',
                       line = list(color = 'rgb(205, 12, 24)', width = 4))
}

p
Run Code Online (Sandbox Code Playgroud)

绘图输出