【问题标题】:Ploty R add_trace with for loop overwrites trace from get(Variable)Plotly R add_trace 与 for 循环覆盖来自 get(Variable) 的跟踪
【发布时间】:2021-04-25 02:49:25
【问题描述】:

我想为不同数量的变量向 Plotly 条形图添加跟踪。因此我想循环遍历变量。我没有收到错误,但最新循环的变量会覆盖以前循环的值。看起来是这样的(v3覆盖plot1中的v2)

df <- as.data.frame(cbind(1:3,11:13,111:113))

plot1 <- plot_ly(df, x = ~ V1
                 , y = 7
                 ,type = 'bar'
)
for(i in c("V2","V3")){
  plot1 <- plot1 %>% add_trace(y = ~ get(i)
                               ,type = 'bar'
  )
}
plot1

但应该看起来像这样(V3 不会覆盖 plot2 中的 V2)

df <- as.data.frame(cbind(1:3,11:13,111:113))    

plot2 <- plot_ly(df, x = ~ V1

                 , y = 7
                 ,type = 'bar'
)
plot2 <- plot2 %>% add_trace(y = ~ V2
                               ,type = 'bar'
  )
plot2 <- plot2 %>% add_trace(y = ~ V3
                             ,type = 'bar'
)
plot2

怎么了?

【问题讨论】:

    标签: r for-loop plotly bar-chart r-plotly


    【解决方案1】:

    这行得通(使用 df[,i] 而不是 ~get(i) 这有点烦人,因为 df 已经定义了:

    df <- as.data.frame(cbind(1:3,11:13,111:113))
    
    plot1 <- plot_ly(df, x = ~ V1
                     , y = 7
                     ,type = 'bar'
    )
    for(i in c("V2","V3")){
      plot1 <- plot1 %>% add_trace(y = df[,i]
                                   ,type = 'bar'
      )
    }
    plot1
    

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 2019-07-14
      • 2022-07-01
      • 2018-04-25
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      相关资源
      最近更新 更多