问题
I have created subplots in Plotly
that each contain a bar chart (or boxplot
) and three trace lines. I have created traces at y= 1,2,3 to act as ablines
like in ggplot
.
What the plots look like:
and
.
Problem:
I want to have it so the bars of the bar chart are in front of the trace lines so you should only be able to see the trace lines in between the bars.
My code currently:
(I have excluded the code that generates the subplots as I don't think it is needed)
generate_plotly_barPlot <- function(dat, showLeg, err) {
p <- plot_ly(x=dat$xVar, # Initialize graph with line y=2
y=2,
type="scatter",
mode="lines",
hoverinfo="none",
layer="below",
line=list(color="grey",
width=2),
showlegend=FALSE) %>%
# Add trace at line y=1
add_trace(x=dat$xVar,
y=1,
type="scatter",
mode="lines",
hoverinfo="none",
line=list(color="grey",
width=1.5,
dash="dot"),
inherit=FALSE,
showlegend=FALSE) %>%
# Add trace at line y=3
add_trace(x=dat$xVar,
y=3,
type="scatter",
mode="lines",
hoverinfo="none",
line=list(color="grey",
width=1.5,
dash="dot"),
inherit=FALSE,
showlegend=FALSE)%>%
# Create Bar Chart
add_trace(x=dat$xVar,
y=dat$CopyNumber,
type="bar",
mode="markers",
color=dat$fillColor,
orientation="v",
inherit=FALSE,
marker=list(opacity=1),
legendgroup=dat$xVar,
showlegend=showLeg,
error_y = list(value=dat[[err]],
color='#000000',
thickness=3,
width=6,
visible=TRUE))
My approach:
I thought that the order the traces were created would define which layer they would be on in the graph, so since I plotted the bar chart after all of the trace lines, it would sit above them.
I also tried creating shapes to be the ablines
but it was really difficult to get them in the correct position for subplots. add_traces
was my best approach. Shapes in plotly have a layer
parameter to define whether to place the shape above or below (see the plotly reference). I was hoping there was something like this that applied to traces, but I couldn't find it.
回答1:
Maybe this could help you started. You did not provide a data set so here is a small made-up example. You can use layout to add a shape (a line in your case) to your graphic. As you can see the bar is above the line. Hope it helps!
plot_ly() %>%
add_bars(x = c("giraffes", "orangutans", "monkeys"), y = c(20, 14, 23)) %>%
layout(shapes = list(list(type = "lines",x0 = -1, x1 = 3, xref = "x", y0 = 3, y1 = 3, yref = "y", layer = "below")))
来源:https://stackoverflow.com/questions/48831856/place-plotly-bar-chart-and-box-plot-in-front-of-line-traces