问题
I am trying to create a Marimekko chart in R using Plotly. Essentially, this is just a stacked, variable-width bar chart with both bars directly adjacent to one another. Currently, my attempt looks like this:
The code to create it is 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()
And the data looks like this:
My goal is simply to have there be no gap between the bars. I have tried to do this with the bargap argument but have read that assigning the bars a width makes Plotly ignore the bargap argument. I've also read a potential workaround is to manually change the bars' offset argument. However, I have many of these figures with varying widths and percents so any solution can't be manual.
回答1:
You can do it by having custom x and using bargap = 0 in layout
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

Created on 2019-11-19 by the reprex package (v0.3.0)
回答2:
A Marimekko chart is more commonly known as a "Mosaic Plot". You can make one in ggplot using ggmosaic, and then convert it to plotly using ggplotly. You did not provide copyable data in the question, so here is an example using the mtcars dataset:
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)
来源:https://stackoverflow.com/questions/58924514/remove-gaps-between-bars-in-plotly