R plotly add_trace to a chart with color groups

John

For data set mtcars, I want to plot a scatter plot (wt v.s. mpg) with am as the color group.

Then I want to add a trace from (2,15) to (3,25).

mtcars$am = as.character(mtcars$am)
plot_ly(mtcars,x = ~ wt, y= ~ mpg, color = ~ am, type='scatter', mode = 'markers') %>% 
    add_trace(x = c(2,15), y = c(3,25), mode="lines")

The code without add_trace works fine. How to add this line?

Edgar Santos

Option 1:

library(plotly)
library(ggplot2)
p <- ggplot(mtcars) + geom_point(aes(x = wt, y =  mpg, col = am)) + geom_segment(aes(x = 2, y = 3, xend = 15, yend = 25))
ggplotly(p)

Option 2:

plot_ly() %>% 
add_trace(data = mtcars,x = ~ wt, y= ~ mpg, color = ~ am, type='scatter', mode = 'markers') %>%
add_trace( x = c(2,15, rep(NA,nrow(mtcars))), y = c(3,25,rep(NA,nrow(mtcars))), mode="lines")

enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Is there a way to not display hover values for add_trace values in R plotly?

R Plotly - add_trace that sums value by group

Plotly R add_trace objects are far apart

add_trace in Plotly in a loop

How to add seperate titles to pie charts created through add_trace in plotly R

add_trace: control the color

plotly-r: specifying size of marker in add_trace() reduces opacity of markers

R Plotly animated chart only showing groups with data in initial frame

How to sort an R Plotly grouped bar chart within groups?

Plotly make marker overlay add_trace

Color in plotly bar chart

add_trace in plotly, which trace to use for my particular graph

Plotly add_trace vs append_trace

Add specific legend to R plotly chart

Plotly: How to add trace to multicategory bar chart?

Plotly Bar chart, add a second factor for coloring, opacity or border color

Color in Multiple Subplots Plotly Chart

Plotting add_trace from within a function: Plotly

R Plotly unable to remove trace 0 from bar chart

Plotly (R) - Pie chart: How to fixate the color assignment color per group?

color and legend in plotly in R

How to define separate color palettes per trace in R plotly plots?

Make plot and trace same color by factor plotly R

Candlestick chart add_trace(mode="markers") gives wrong output

Plotly: How to animate a bar chart with multiple groups using plotly express?

R Plotly: How to set the color of Individual Bars of a Waterfall Chart in R Plot.ly?

Is there a way to add text to the `y2` axis of a plotly chart in R?

How to add bordered data labels to R plotly bar chart?

How to add text label to R plotly aggregate chart?