Reputation: 1611
I have a bar plot with bars colored according to a factor variable. I need to place a target marker on each bar at a designated location. I am able to place the marker on the plot without issue, but in the legend, the target marker appears three times, while I would only like it to appear once. I believe this behavior is linked to the coloring of the bars, but this coloring is something that must be retained. Can anybody provide me with a solution so that the target marker only appears on the legend only once?
library(tidyverse)
library(plotly)
data.frame(grp = c("x", "y", "z") %>% as.factor,
vals = c(10, 15, 20)) %>%
plot_ly(
x = ~vals,
y = ~grp,
color = ~grp,
colors = c("red", "green", "blue"),
type = "bar"
) %>%
add_markers(name = "target",
x = 17,
marker = list(
color = "black")
)
Upvotes: 0
Views: 344
Reputation: 3671
Arguments in plot_ly
will be set for all traces as long as there are not overwritten. In your case color = ~grp
inside the plot_ly
function will group each trace by grp
.
An easy option is to define the bars with its colors in an own trace.
Code
data.frame(grp = c("x", "y", "z") %>% as.factor,
vals = c(10, 15, 20)) %>%
plot_ly(
x = ~vals,
y = ~grp
) %>%
add_bars(color = ~grp,
colors = c("red", "green", "blue")) %>%
add_markers(name = "target",
x = 17,
marker = list(
color = "black")
)
In this code, x and y are shared by bars and markers but colors are defined separately in each trace. Therefore you get individual legends for bars and a single legend for markers.
Upvotes: 1