消除情节之间的酒吧之间的差距

时间:2019-11-18 23:36:50

标签: 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参数。但是,我有很多这样的数字,它们的宽度和百分比都不同,所以任何解决方案都无法手动完成。

2 个答案:

答案 0 :(得分:2)

Marimekko图表通常被称为“马赛克图”。您可以使用ggplotggmosaic中制作一个,然后使用ggplotly将其转换为绘图。您没有在问题中提供可复制的数据,因此这是使用mtcars数据集的示例:

library(dplyr)
library(ggmosaic)
library(plotly)

p <- mtcars %>%
       lapply(as.factor) %>%
       as.data.frame() %>%
       count(cyl, gear)  %>%
       ggplot() +
         geom_mosaic(aes(weight = n, x = product(cyl), fill = gear)) +
         labs(x = 'Cylinders', y = 'Gears')
ggplotly(p)

enter image description here

答案 1 :(得分:1)

您可以通过自定义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(v0.3.0)于2019-11-19创建