Add multiple lines to a plot_ly graph with add_trace - r
I found an example to add lines to a plot_ly plot by using the add_trace command. How can I add a list of lines to plot without using add_trace multiple times?
I tried a for loop to add the traces but this doesn't work as expected.
my_lines <- list(
list(x=1:10, y=2:11, color='red'),
list(x=1:10, y=0:9, color='blue'),
list(x=1:10, y=3:12, color='green')
)
p <- plot_ly()
p
for(line in my_lines) { p <- add_trace(p, y=line[['y']], x=line[['x']],
marker=list(color=line[['color']]))
}
p
But this for example works as expected.
p <- plot_ly()
p <- add_trace(p, y=my_lines[[1]][['y']], x=my_lines[[1]][['x']],
marker=list(color=my_lines[[1]][['color']]))
p <- add_trace(p, y=my_lines[[2]][['y']], x=my_lines[[2]][['x']],
marker=list(color=my_lines[[2]][['color']]))
p <- add_trace(p, y=my_lines[[3]][['y']], x=my_lines[[3]][['x']],
marker=list(color=my_lines[[3]][['color']]))
p
I believe with the release of plotly 4.0 calling any of the add_* family of functions forces evaluation so there is no need to call evaluate = T anymore
So, something like this should work fine:
devtools::install_github("ropensci/plotly")
library(plotly)
p <- plot_ly()
for(i in 1:5){
p <- add_trace(p, x = 1:10, y = rnorm(10), mode = "lines")
}
p
You need to set evaluate = TRUE to force evalutation / avoid lazy evaluation
p <- plot_ly()
p
for(line in my_lines) { p <- add_trace(p, y=line[['y']], x=line[['x']],
marker=list(color=line[['color']]),
evaluate = TRUE)
}
p
You can transform your inputs into a long-form data frame first, then plot using the split argument.
library(plotly)
library(reshape2)
my_lines = data.frame(x = 1:10, red = 2:11, blue = 0:9, green = 3:12)
my_lines_long = reshape2::melt(my_lines, id.vars = "x")
fig = plotly::plot_ly(my_lines_long, x = ~x, y = ~value, split = ~variable,
marker=list(color=~variable))
fig
Related
Plotting box-plots with for loop in Plotly
I made several plots with this lines of code: dataset_numeric = dplyr::select_if(dataset, is.numeric) par(mfrow=c(3,3)) for(i in 1:9) { boxplot(dataset_numeric[,i], main=names(dataset_numeric)[i]) } And output from this plot is pic below : So I want to do same but now with library(Plotly) so can anybody help me how to do that ?
The following uses packages tidyr and ggplot2. First, the data are converted to a long table with pivot_longer, and then piped to ggplot. One issue to note in the example with one box only is that an explicit x aesthetic is needed, otherwise only the first box may be shown. library("dplyr") library("plotly") library("ggplot2") library("tidyr") dataset <- as.data.frame(matrix(rnorm(99), ncol=9)) p <- pivot_longer(dataset, cols=everything()) %>% ggplot(aes(x=0, y = value)) + geom_boxplot() + facet_wrap( ~ name) ggplotly(p) Edit: a first had still an issue, that could be solved by adding x=0.
I you want to use plotly and put all variables in the same graph, you can use add_trace() in a for loop to do what you want. library(plotly) dataset_numeric = dplyr::select_if(iris, is.numeric) fig <- plot_ly(data = dataset_numeric, type = "box") for (i in 1:ncol(dataset_numeric)) { fig <- fig %>% add_trace(y = dataset_numeric[,i]) } fig If you want to have separate plot for each variable, you can use subplot() all_plot <- list() for (i in 1:ncol(dataset_numeric)) { fig <- plot_ly(data = dataset_numeric, type = "box") %>% add_trace(y = dataset_numeric[,i]) all_plot <- append(all_plot, list(fig)) } plt <- subplot(all_plot) plt
How to make many plotly charts each one in its own Viewer window?
I'm making some visualization using R Studio. I have a list of dataframes: tickers_df <- read.csv('tickers.csv') v_df <- split(tickers_df, tickers_df$pair_code) Now I want to make a plot for each dataframe within v_df in its own Viewer window. I'm doing: for (pair_df in v_df) { col_name <- names(pair_df)[4:9] colors <- c('green', 'darkgreen', 'red', 'darkred', 'blue', 'darkblue') df_layout <- data.frame(col_name, colors) p <- plot_ly() for (i in 1:nrow(df_layout)) { col_name <- as.character(df_layout[i, 1]) p <- add_trace( p, x = pair_df$step, y = pair_df[, col_name], name = col_name, type = 'scatter', mode = "lines", line = list(color = df_layout[i, 2], width = 1) ) p <- layout(p, title = pair_df$pair_code[[1]]) } p } But this code doesn't work as expected - it shows no charts at all. How can I draw many plotly charts within a loop? And btw what is the meaning of last line with only p variable? Like in this example: p <- plot_ly( x = df$time.1, y = df$total_profit, line = list(color = 'darkred')) p #what is this standing for?
R Plotly Add Trace within Loop
I have an issue with using loops to add trace in plotly, though I have no idea what the cause is. If I try to make a plot using the method for P below, only the data for last column (HORSE) is shown. Rabbit and Dog still show up, but both display values for Horse. If, however, I use the P1 method the graph works perfectly. I would really like to be able to do this within a loop as the length of columns varies. df <- data.frame(AGE = c(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5), YEAR = c(2010,2011,2012,2013,2014,2015,2016,2017,2010,2011,2012,2013,2014,2015,2016,2017,2010,2011,2012,2013,2014,2015,2016,2017,2010,2011,2012,2013,2014,2015,2016,2017,2010,2011,2012,2013,2014,2015,2016,2017,2010,2011,2012,2013,2014,2015,2016,2017), RABBIT = c(0,5,2,6,8,5,8,4,3,6,2,7,5,5,9,9,1,4,4,6,5,3,7,7,6,8,2,6,9,1,9,1,1,2,10,1,10,10,4,2,4,8,7,0,3,4,5,7), DOG = c(2,5,0,8,2,5,9,5,10,5,10,3,8,9,2,7,5,1,1,4,6,7,7,0,6,5,7,2,2,9,4,2,6,0,7,1,7,6,9,9,9,5,5,9,0,9,10,2), HORSE = c(7,1,9,10,6,6,5,1,4,5,0,3,0,3,2,4,3,6,1,9,6,4,3,1,7,8,4,1,8,6,5,9,2,0,5,5,6,1,1,7,4,9,5,0,8,1,5,7) ) L <- c("RABBIT","DOG","HORSE") P <- plot_ly(data = df) for(i in 1:length(L)){ P<-add_trace(P, y=~df[[L[i]]], x=~df$AGE, frame =~df$YEAR, type="scatter", mode="lines", name = L[i]) } P1 <- plot_ly(data = df) P1 <- add_trace(P1, y=~df[[L[1]]], x=~df$AGE, frame =~df$YEAR, type="scatter", mode="lines", name = L[1]) P1 <- add_trace(P1, y=~df[[L[2]]], x=~df$AGE, frame =~df$YEAR, type="scatter", mode="lines", name = L[2]) P1 <- add_trace(P1, y=~df[[L[3]]], x=~df$AGE, frame =~df$YEAR, type="scatter", mode="lines", name = L[3]) P P1
You can use this solution: P <- plot_ly(data = df) for(k in 1:length(L)) { dfk <- data.frame(y=df[[L[k]]], AGE=df$AGE, YEAR=df$YEAR) P <- add_trace(P, y=~y, x=~AGE, frame =~YEAR, data=dfk, type="scatter", mode="lines", name = L[k]) }
R plotly Issues with hovering text in a trace loop
Following this post and this answer I have an additional question: library(plotly) # Create data dat=data.frame(group = factor(rep(LETTERS[1:4], each=10)), my_x = rep(1:10, 4), my_y = rnorm(40)) str(dat) # Let's do a first plot p<-plot_ly(dat) # Add a trace for each group using a loop for(i in 1:length(levels(dat$group))){ subs <- subset(dat, group == levels(dat$group)[i]) p<-add_trace(p = p, data = subs, y=~my_y, x=~my_x , name=levels(dat$group)[i], type="scatter", mode="markers+lines", hoverinfo="text", text=~paste0(levels(dat$group)[i], ": x=", round(my_x, 2), "y=", round(my_y, 2))) } p Can anybody tell me why it is that when I hover over the data points, each of the labels shows the correct x and y values, however, they are all labelled as 'D:', while the legend shows the lines resemble A, B, C & D. I would like the hover text to be labeled correctly.
It could be an issue with the use of ~ in text. Try by creating the 'text' using the 'subs' data separately and then pass it on the add_trace p <- plot_ly() lvls <- levels(dat$group) for(i in seq_along(lvls)){ subs <- droplevels(subset(dat, group == lvls[i])) text1 <- with(subs, paste0(lvls[i], ": x=", round(my_x, 2), "y=", round(my_y, 2))) p <- add_trace(p, data = subs, x = ~my_x, y = ~my_y, name = lvls[i], type = 'scatter', mode = 'markers+lines', hoverinfo='text', text=text1) } p -output
Programmatically add layers to plotly in R
I am trying to add layers in plotly programmatically but can't seem to get around it's lazy evaluation. Example: p <- plot_ly() for(kk in 1:5) { tmp <- cbind(rnorm(1) + 0.05*rnorm(15),rnorm(1) + 0.05*rnorm(15)) p %<>% add_trace(x = tmp[,1], y = tmp[,2], type = "scatter", mode = "markers") } In this example I was trying to plot a gaussian mixture model, however, the arguments to plotly aren't evaluated until they are viewed, so all five layers contain only the final value of tmp. The command plotly_build is supposed force evaluation but I can't find examples of its usage and apparently I'm doing it wrong. p <- plot_ly() for(kk in 1:5) { tmp <- cbind(rnorm(1) + 0.05*rnorm(15),rnorm(1) + 0.05*rnorm(15)) p %<>% add_trace(x = tmp[,1], y = tmp[,2], type = "scatter", mode = "markers") plotly_build(p) } Still gives the same result. What am I doing wrong?
p <- plot_ly() for(kk in 1:5) { tmp <- cbind(rnorm(1) + 0.05*rnorm(15),rnorm(1) + 0.05*rnorm(15)) p %<>% add_trace(x = tmp[,1], y = tmp[,2], type = "scatter", mode = "markers", evaluate = TRUE) } There is an evaluate argument to plotly.