提问人:Koda 提问时间:11/9/2023 更新时间:11/9/2023 访问量:30
在循环中创建数据帧中所有列的 Plotly 图
Create a Plotly plot of all the columns in a dataframe in a loop
问:
我想使用循环将每列作为数据帧中的单独行绘制到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)
有什么想法吗?
答:
1赞
Friede
11/9/2023
#1
我认为问题是由于两个错别字造成的,当然,请从中删除:~
y = ~t_df[,i]
i = 3
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])
}
评论