Reputation: 321
The code I am using is:
DF <- data.frame(
stringsAsFactors = FALSE,
Month = c("2019-Dec","2019-Dec",
"2019-Dec","2019-Dec","2020-Jan","2020-Jan","2020-Jan", "2020-Jan"),
Week = c(4L, 4L, 5L, 5L, 1L, 1L, 1L, 2L),
Cat = c("A", "B", "A", "C", "A", "B", "C", "A"),
n = c(17L, 6L, 21L, 10L, 19L, 20L, 12L, 14L)
)
fig <- DF %>%
split(DF$Month) %>%
purrr::map(~{
plot_ly(colors = c("A" = "red", "B" = "green", "C" = "blue", "D" = "black")) %>%
add_bars(data = .x,
x = .x$Week,
y = .x$n,
type = 'bar',
split = .x$Cat,
color = .x$Cat,
legendgroup = .x$Cat) %>%
layout(xaxis = list(showticklabels = FALSE, title = unique(.x$Month)))
})
subplot(fig, shareY = TRUE, titleX = TRUE, margin = 0) %>%
layout(barmode = 'stack', showlegend =TRUE)
The problem I am facing here is the duplicate legend on right. And I also want the Month title vertically not horizontally.
Thanks in advance!
Upvotes: 1
Views: 723
Reputation: 817
here is a solution to avoid duplicate legend using showlegend=FALSE/TRUE
with a parameter. I am not sure if plotly lets you rotate the axis title. But maybe you could play around with individual axis ticks, which can be rotated?
"%>%" <- magrittr::"%>%"
DF_grp <- DF %>%
split(DF$Month)
p <- lapply(seq_along(DF_grp),function(idx) {
show_legend <- switch(idx,
"1"=TRUE,
"2"=FALSE)
plotly:: plot_ly(colors = c("A" = "red",
"B" = "green",
"C" = "blue",
"D" = "black")) %>%
plotly::add_bars(data=DF_grp[[idx]],
x=~Week,
y=~n,
type="bar",
split=~Cat,
color=~Cat,
legendgroup=~Cat,
showlegend=show_legend) %>%
plotly::layout(xaxis=list(showticklabels=F,
title=unique(DF_grp[[idx]]$Month)),
barmode="stack",
showlegend =TRUE)
})
p %>%
plotly::subplot(shareY = TRUE,
titleX = TRUE,
margin = 0)
Upvotes: 1