【问题标题】:Multiple line chart using plotly r使用 plotly r 的多折线图
【发布时间】:2019-01-02 12:59:42
【问题描述】:

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

  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 以从图表中删除,即使它不在我循环添加行的列名中。

【问题讨论】:

    标签: r dataframe plotly r-plotly


    【解决方案1】:

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

    1. 当您最初定义 p 并包含 datax 参数时,会创建一个跟踪 -- trace 0。您可以在不提供任何数据或 x 值的情况下定义绘图,只需使用 p &lt;- plot_ly() 以及任何所需的布局功能即可开始。
    2. 当您遍历列名时,您的 x 轴列 Month_Considered 是集合的一部分。您可以通过使用setdiff()(base R 的一部分)来排除此问题,为Months_Considered 创建一个包含所有列名 except 的向量

    将这两件事放在一起,(许多可能的) 完成您的目标的一种方法如下:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2020-09-30
      • 2020-10-06
      • 2021-01-10
      相关资源
      最近更新 更多