循环创建数据框中所有列的绘图

问题描述 投票:0回答:1

我想使用循环将每一列作为数据框中的单独行绘制成 Plot_ly 散点图。该循环将每一列绘制为与最后一列相同的值。这是一个简化的示例:

library(plotly)

# Creating a sequence of dates
dates <- seq(as.Date("2023-01-01"), by = "day", length.out = 5)  
# Creating the dataframe with 5 rows and 5 columns
t_df <- data.frame(
  Date = dates,
  Column2 = c(1, 2, 3, 4, 5),
  Column3 = c(6, 7, 8, 9, 10),
  Column4 = c(11, 12, 13, 14, 15),
  Column5 = c(16, 17, 18, 19, 20)
)
#Initializing the plot
plot <- plot_ly(data = t_df)
#loop to add each trace to the plot
for (i in 2:ncol(t_df)){
  i = 3
  plot <- add_trace(plot, data = t_df, x = ~Date, y = ~t_df[,i], type = 'scatter', mode = 'lines', name = names(t_df)[i])
}
print(plot)

这是当前脚本产生的结果:

有什么想法吗?

r for-loop plot plotly
1个回答
0
投票

我认为这只是一个拼写错误,从

~
中删除
y = ~t_df[,i]

for (i in 2:ncol(t_df)) { 
  plot <- add_trace(plot, data = t_df, x = ~Date, y = t_df[, i], 
                    type = 'scatter', mode = 'lines', name = names(t_df)[i])
}
© www.soinside.com 2019 - 2024. All rights reserved.