Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a horizontal line to a plotly bar graph

I'm trying to use R plotly's bar type plot to generate a plot with horizontally laid out boxes and add to that a horizontal line which is in their background (rather than goes on top of them). In addition, I would like the line to extend symmetrically one box unit in each direction.

Here's what I'm doing:

plot.df <- data.frame(x = paste0("LONG NAME ",1:6),y = 0.2,width=0.75,group = c("A","B","B","B","C","A"),stringsAsFactors = F)
plot.df$group <- factor(plot.df$group)


plotly::plot_ly(plot.df) %>%
  plotly::add_trace(x=~x,y=~y/2,type='scatter',mode='lines',line=list(color='black'),showlegend=F) %>%
  plotly::add_bars(x=~x,y=~y,width=~width,color=~group) %>%
  plotly::layout(xaxis=list(title=NA,zeroline=F,tickangle=45),yaxis=list(title=NA,zeroline=F,showgrid=F,range=c(0,1),showticklabels=F))

Which gives:

enter image description here

My questions are:

  1. How to extend the the line in both directions
  2. How to put the line in the background so it does not run over the boxes
  3. I specified plot.df$y as 0.2 but the yaxis range to be c(0,1) so that the boxes don't look like long bars. But then the legend appears too high. Any better way to get square boxes with the legend appearing lower than it currently is?
like image 762
dan Avatar asked Mar 14 '19 19:03

dan


1 Answers

For the horizontal line you can see Horizontal/Vertical Line in plotly

with

layout(legend =list(x = 1 ,y =0 ))

you can solve the legend problem

I could not solve your second point (put the bar in the background). I hope it helps:

hline <- function(y = 0, color = "blue") {
  list(
    type = "line", 
    x0 = 0, 
    x1 = 1, 
    xref = "paper",
    y0 = y, 
    y1 = y, 
    line = list(color = color)
  )
}

plot_ly(plot.df) %>%
  add_bars(x=~x,y=~y,width=~width,color=~group, hoverinfo = "text") %>%
  layout(shapes = list(hline(0.1)))%>%
  layout(legend =list(x = 1 ,y =0 ))%>%
  layout(xaxis=list(title=NA,zeroline=F,tickangle=45),yaxis=list(title=NA,zeroline=F,showgrid=F,range=c(0,1),showticklabels=F))
like image 55
João Avatar answered Oct 31 '22 09:10

João