This question is related to some others on SO but I haven't found a solution yet.
I'm looking to use plotly
's dropdown functionality to select which variable gets plotted on the x-axis, similar to this question/answer that's been super helpful in getting me to where I am now.
I'm now trying to use the color
argument in plot_ly
to color the markers in my plot. However, when I use the dropdown to change the x-variable, it seems like the data gets jumbled or mixed up. Here's a minimal reproducible example:
library(plotly)
plot_ly(data = iris, x = ~Sepal.Length, y = ~Sepal.Width, color = ~Species,
type ="scatter", mode = "markers",text = ~Species,
hovertemplate = paste('<i>Species</i>: %{text}',
'<br><b>X</b>: %{x}<br>',
'<b>Y</b>: %{y}')
) %>%
layout(
annotations = list(
list(
text = "<b>X-Axis Variable:</b>", x=0.05, y=1.13,
xref='paper', yref='paper',xanchor = "left", showarrow=FALSE
)
),
updatemenus = list(
list(
type = "list",
x = 0.25,
xanchor = "left",
y = 1.15,
buttons = list(
list(
method = "update",
args = list(list(x = list(iris$Sepal.Length)),
list(xaxis = list(title = "Sepal.Length"))),
label = "Sepal.Length"
),
list(
method = "update",
args = list(list(x =list(iris$Sepal.Width)),
list(xaxis = list(title = "Sepal.Width"))),
label = "Sepal.Width"
),
list(
method = "update",
args = list(list(x = list(iris$Petal.Length)),
list(xaxis = list(title = "Petal.Length"))),
label = "Petal.Length"
),
list(
method = "update",
args = list(list(x = list(iris$Petal.Width)),
list(xaxis = list(title = "Petal.Width"))),
label = "Petal.Width"
)
)
)
)
)
Which produces a plot that initially looks correct but its behavior is not correct:
We know it's not correct because when we change the x-variable to Sepal.Width
, which is the same as the y-variable and therefore should result in a simple line of points along the y=x axis, we're left with the plot below:
There's some talk on SO from questions like this that suggests that selecting a color variable isn't supported with the R-plotly API but I'm not interested in changing the color. Interestingly, this issue disappears when I remove the color = ~Species
argument from my plot.
Thanks all - not sure where the best place to look is!