简体   繁体   English

向可绘制的条形图添加水平线

[英]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).我正在尝试使用R plotlybar来生成一个带有水平布局框的图,并在其背景中添加一条水平线(而不是在它们之上)。 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:这使:

在此处输入图片说明

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.我指定plot.df$y为0.2,但yaxis的范围是c(0,1)这样的箱子看上去并不像长条。 But then the legend appears too high.但随后传说就显得太高了。 Any better way to get square boxes with the legend appearing lower than it currently is?有什么更好的方法可以让方块的图例看起来比现在低?

For the horizontal line you can see Horizontal/Vertical Line in plotly对于水平线,您可以在 plotly 中看到Horizo​​ntal/Vertical Line

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM