首页 > 解决方案 > 删除 Plotly 中的条之间的间隙

问题描述

我正在尝试使用 Plotly 在 R 中创建一个 Marimekko 图表。本质上,这只是一个堆叠的、可变宽度的条形图,两个条形直接相邻。目前,我的尝试如下所示:

在此处输入图像描述

创建它的代码在这里:

bar.test <- plot_ly(type = "bar") %>% 
  layout(title = paste0("Newark Charter vs District BTO Makeup"),
         xaxis = list(title = ""),
         yaxis = list(title = "Percent BTO", tickformat = "%")) %>% 
  add_trace(x = ~test1$sch.type, y = ~test1$y, width = ~test1$width, 
            marker = list(color = c(blue.dark.opq, red.opq.2, blue.dark.opq, red.opq.2) ,
                            line = list(color = 'rgba(0,0,0,1)' , width = 2))) %>% 
  add_annotations(x = ~test1$sch.type, y = ~test1$annotation.y,
                  text = paste0("<b>", 100*round(test1$y, 3), "%"),
                  showarrow = F,
                  font = list(size = 14, color = 'rgba(0,0,0,1)')) %>% 
  add_annotations(x = ~test1$sch.type, y = ~test1$all.y,
                  text = paste0(test1$all.count), showarrow = F,
                  font = list(size = 14, color = 'rgba(0,0,0,1)')) %>% 
  hide_legend()

数据如下所示:

在此处输入图像描述

我的目标只是让钢筋之间没有间隙。我试图用bargap参数来做到这一点,但已经读到为条分配宽度会使 Plotly 忽略该bargap参数。我还阅读了一个潜在的解决方法是手动更改条形图的offset参数。但是,我有许多具有不同宽度和百分比的数字,因此任何解决方案都不能是手动的。

标签: rbar-chartr-plotly

解决方案


您可以通过自定义xbargap = 0在布局中使用来做到这一点

library(plotly)
#> Loading required package: ggplot2
#> 
#> Attaching package: 'plotly'
#> The following object is masked from 'package:ggplot2':
#> 
#>     last_plot
#> The following object is masked from 'package:stats':
#> 
#>     filter
#> The following object is masked from 'package:graphics':
#> 
#>     layout

test1 <- data.frame(
    city.state = "Newark",
    sch.type = c("Charter", "Charter", "District", "District"),
    bto.stat = c(0,1,0,1),
    y = c(.7, .3, .1, .9),
    width = c(.3, .3, .7, .7),
    x = c(.15, .15, .65, .65),
    annotation.y = c(.3, .8, .05, .55),
    all.count = c(46000, 46000, 99000, 99000),
    all.y = c(1,1,1,1)
    )

bar.test <- plot_ly(type = "bar") %>%
    add_trace(x = test1$x,
              y = test1$y,
              width = test1$width,
              marker = list(
                color = c("blue", "red", "blue", "red") ,
                line = list(color = 'rgba(0,0,0,1)' , width = 2)
                )
              ) %>%
    layout(bargap = 0)

bar.test

reprex 包(v0.3.0)于 2019 年 11 月 19 日创建


推荐阅读