I am trying to transform a facet plot into html style using ggplotly()
function in plotly
package.
Everything is fine but the y-axis is overlapped. And I don't know how to solve it.
The reproducible code is below:
library(tidyverse)
library(plotly)
state <- 1:31 %>% as.character()
disease <- 1:40 %>% as.character()
city <- LETTERS[1:2]
value <- runif(n = 31*40*2)
df <- expand.grid(state = state,
disease = disease,
city = city) %>% cbind(value)
p <- df %>%
ggplot(aes(x = city, y = disease, fill = value)) +
geom_tile() +
scale_fill_gradient(high = '#FF0000', low = 'white') +
theme(axis.line = element_line(linetype = 'solid')) +
theme_classic() +
scale_x_discrete(expand = c(0,0)) +
scale_y_discrete(expand = c(0,0)) +
facet_wrap(vars(state))
p
web_p <- ggplotly(p)
web_p
Unfortunately, the new guide_axis()
tricks included in ggplot2 3.3, using the n.dodge and check.overlap arguments, do not have an effect on your ggplotly()
output currently: https://www.tidyverse.org/blog/2020/03/ggplot2-3-3-0/#rewrite-of-axis-code
One other alternative would be to use dual y axes with numeric data, and split your labels between the two, but again, plotly would ignore that.
Quite a few features of ggplot2 will not easily translate into an interactive plotly visualisation.
The best workaround I can think of is to tweak your break label font size, and change the layout of your faceting in order to give more space for the labels (given that there is a lot less information to display on your x axis):
library(tidyverse)
state <- 1:31 %>% as.character()
disease <- 1:40 %>% as.character()
city <- LETTERS[1:2]
value <- runif(n = 31*40*2)
df <- expand.grid(state = state,
disease = disease,
city = city) %>% cbind(value)
p <- df %>%
ggplot(aes(x = city, y = disease, fill = value)) +
geom_tile() +
scale_fill_gradient(high = '#FF0000', low = 'white') +
theme(axis.line = element_line(linetype = 'solid')) +
theme_classic() +
scale_x_discrete(expand = c(0,0)) +
scale_y_discrete(expand = c(0,0)) +
facet_wrap(vars(state), nrow = 3) +
theme(axis.text.y = element_text(size = 4))
p
Created on 2020-10-29 by the reprex package (v0.3.0)
These settings will be kept when converting to a plotly visualisation:
web_p <- ggplotly(p)
web_p