2

我有一个数据框,我试图将其绘制为多折线图。以下是数据框的外观:

  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

当我遍历以绘制下面的多行时,是使用的代码。

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

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

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

4

1 回答 1

5

看起来你被两件事绊倒了:

  1. 当您最初定义p并包含dataandx参数时,创建了一个跟踪 -- trace 0。您可以在不提供任何数据或 x 值的情况下定义绘图,只需使用p <- plot_ly()任何所需的布局功能即可开始。
  2. 当您遍历列名时,您的 x 轴列Month_Considered是集合的一部分。您可以通过使用setdiff()(base 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

绘图输出

于 2018-07-25T17:28:08.047 回答