Hello everyone here is my issue:
In python, I can easily do a multiple-line plot from my raw data in one line using plotly:
import pandas as pd
import numpy as np
import plotly.express as px
#generating the data
I=np.linspace(0, 10, 100)
data={'0 min':np.cos(I)*0.5,
'10 min':np.cos(I)*1,
'20 min':np.cos(I)*2,
'30 min':np.cos(I)*4}
I=np.linspace(250, 349, 100)
df=pd.DataFrame(data,index=I)# df of my raw data
px.line(df, x=df.index, y=df.columns)
However, in R, with the same data :
library(plotly)
I<-seq(0, 10, length.out=100)
df = data.frame(t0min=cos(I)*0.5,
t10min=cos(I)*1,
t20min= cos(I)*2,
t30min=cos(I)*4)
I<-seq(250, 349, length.out=100)
rownames(df)<-I
this does not work:
plot_ly(df,
x = rownames(df),
y = colnames(df),
name = ~colnames(df),
type = 'scatter',
mode = 'lines')#does not work
The only solution that I found is to reshape my data frame entirely :
name=vector()
x=vector()
Y=vector()
for (i in colnames(df)){
name=c(name,rep(i,length(df[,i])) )
x=c(x, rownames(df[i]))
Y=c(Y, df[,i])
}
DF=data.frame(x, Y, name)
plot_ly(DF,
x = ~x,
y = ~Y,
color = ~name,
name = ~name,
type = 'scatter',
mode = 'lines')
Is there a simple solution to achieve the same result in R without reshaping the entire data frame?
AFAIK there isn't. But you could simplify the reshaping of your data considerably by using e.g. tidyr::pivot_longer
. Also, instead of adding your I
column as row names (which TBMK is different from the pandas concept of an index column) add it as a column to your dataset:
library(plotly)
I <- seq(0, 10, length.out = 100)
df <- data.frame(
t0min = cos(I) * 0.5,
t10min = cos(I) * 1,
t20min = cos(I) * 2,
t30min = cos(I) * 4
)
df$I <- I
df %>%
tidyr::pivot_longer(-I) %>%
plot_ly(
x = ~I,
y = ~value,
name = ~name,
type = "scatter",
mode = "lines"
)