I have shiny app that has multiple plots with the same x-axis, plots need to be aligned vertically without merging, i.e.: plots must be independent shiny objects from each other. See below reproducible example:
library(ggplot2)
library(shiny)
# example data
df1 <- mtcars
# my custom theme, tried many variants, seems impossible?
myTheme <- function(){
theme(legend.position = "none",
plot.background = element_rect(fill = "lightblue"),
axis.text.y = element_text(margin = margin(t = 0, r = 0, b = 0, l = 2, unit = "cm")),
axis.title.y = element_text(margin = margin(t = 0, r = 0, b = 0, l = 1, unit = "cm")),
plot.margin = unit(c(0, 0, 0, 1), "cm")
)}
# The App with 2 plots
runApp(
shinyApp(
ui = bootstrapPage(
plotOutput('plot1', width = 800, height = 200),
plotOutput('plot2', width = 800, height = 100)
),
server = function(input, output) {
output$plot1 <- renderPlot({
ggplot(df1, aes(mpg, gear)) +
geom_point() +
coord_cartesian(xlim = c(15, 25)) +
myTheme()
})
output$plot2 <- renderPlot({
ggplot(df1[ df1$gear %in% c(3, 5), ], aes(mpg, gear)) +
scale_y_continuous(name = "longName", breaks = c(3, 5), labels = c("myLongThreeeee", "My Longggg FIVE")) +
geom_area() +
coord_cartesian(xlim = c(15, 25)) +
myTheme()
})
}
))
I tried to set my own myTheme()
with different settings on margin, etc. seems like it is impossible?
If impossible, not very pretty solution is suggested here, I will just pad Y-tick labels using single width font, something like:
scale_y_continuous(labels = function(label) sprintf('%15.2f', label)) +
Other alternatives?
Note: I am aware of many packages (grid, cowplot, egg, patchwork, etc) that merge plots into one ggplot object and align x-axis, then print. In my case they need to be separate, as user can change some ui settings, and only affected plots should refresh.
TL;DR: Is it possible to set fixed size for "axis title" and "axis tick labels" space in centimetres, points, e.g.: 1cm, 4cm?
Related post about plotly: Shiny - align plots axis