我想使用循环将每一列作为数据框中的单独行绘制成 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)
有什么想法吗?
我认为这只是一个拼写错误,从
~
中删除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])
}