删除 Plotly 中条形之间的间隙

标签 r bar-chart r-plotly

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

enter image description here

创建它的代码在这里:

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

数据看起来像这样:

enter image description here

我的目标只是让条形之间没有间隙。我曾尝试使用 bargap 参数来执行此操作,但已阅读到为条形分配宽度会使 Plotly 忽略 bargap 参数。我还读过一个潜在的解决方法是手动更改条形图的 offset 参数。但是,我有许多这样的图形,宽度和百分比各不相同,因此任何解决方案都无法手动完成。

最佳答案

您可以通过自定义 x 并在布局中使用 bargap = 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 package 创建于 2019-11-19 (v0.3.0)

关于删除 Plotly 中条形之间的间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58924514/

相关文章:

使用 id、时间和具有多个数据变量的一列 reshape R 中的数据框

python - R 或 Python 中的频繁模式增长

html - 如何调整包含plotly的div以绘制尺寸,使其不与文档重叠

javascript - 只有 1 个结果时如何限制谷歌条形图的宽度?

jquery - C3 图表不需要 y 轴上的小数

r - ggplotly堆叠条形图过滤后未调整大小

plot - 删除 Plotly 中图表之间的间隙

r - R中使用tcltk的多个组合框

r - 更新 R Shiny 中动态创建的 selectInput 框的选择

svg - 如何在 SVG 中创建这个形状?