Setting Graph Size in ggplot2

How to Set Graph Size in ggplot2 with Plotly.


Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Sign up for early access now.

Default plot

library(plotly)
library(ggplot2)

p <- ggplot(mpg, aes(displ, hwy)) + geom_point()+ 
  theme(
  plot.margin = margin(1, 1, 1, 1, "cm"),
  panel.background = element_rect(fill = "white"),
  plot.background = element_rect(
    fill = "grey90",
    colour = "black"
  )
)

ggplotly(p)

Add margin

To add margin use plot.margin().

For the argument you can either use margin(2, 2, 2, 2, "cm") or unit(c(2,2,2,2), "cm").

This two arguments are shorthand for margin: * t = 2 - top * r = 2 - right * b = 2 - bottom * l = 2 - left * unit = "cm"

library(plotly)
library(ggplot2)

p <- ggplot(mpg, aes(displ, hwy)) + geom_point()+ 
  theme(
  plot.margin = margin(1, 1, 2, 2, "cm")
)

ggplotly(p)

Change background colour

To change the colour of the plot background panel.background().

To change the colour of the background around the plot use plot.background().

library(plotly)
library(ggplot2)

p <- ggplot(mpg, aes(displ, hwy)) + geom_point()+ 
  theme(
  plot.margin = margin(1, 1, 1, 1, "cm"),
  panel.background = element_rect(fill = "white"),
  plot.background = element_rect(
    fill = "grey90",
    colour = "black"
  )
)

ggplotly(p)

What About Dash?

Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly() 
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... ) 

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new()
app$layout(
    htmlDiv(
        list(
            dccGraph(figure=fig) 
        )
     )
)

app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)