Trexion Kameha
Trexion Kameha

Reputation: 3580

R - Changing ggplot plot size in jupyter

Using R in a jupyter notebook, first I set the plot size universally. Second, I would like to plot one single plot with a different size.

## load ggplot2 library
library("ggplot2")
## set universal plot size:
options(repr.plot.width=6, repr.plot.height=4)

## plot figure. This figure will be 6 X 4
ggplot(iris, aes(x = Sepal.Length, y= Sepal.Width))   +  geom_point() 

## plot another figure. This figure I would like to be 10X8
ggplot(iris, aes(x = Sepal.Length, y= Sepal.Width))   +  geom_point() + HOW DO i CHANGE THE SIZE?

As you can see, I would like to change the second plot (and only the second plot) to be a 10X8. How do I do this?

Sorry for a potentially dumb question, as plot sizing is typically not an issue in Rstudio.

Upvotes: 31

Views: 23497

Answers (4)

ChillOut
ChillOut

Reputation: 31

A solution that doesn't involve using external packages is this.

fig <- function(width, heigth){
 options(repr.plot.width = width, repr.plot.height = heigth)
 }

Just put fig(10, 4), for example, in the cell that generates the plot, and the plot will be scaled accordingly

Source: https://www.kaggle.com/getting-started/105201

Upvotes: 3

testlnord
testlnord

Reputation: 458

I've found another solution which allows to set plot size even when you make plots inside function or a loop:

pl <- ggplot(iris, aes(x = Sepal.Length, y= Sepal.Width)) + geom_point()
print(pl, vp=grid::viewport(width=unit(10, 'inch'), height=unit(8, 'inch')))

Upvotes: 4

Ken Williams
Ken Williams

Reputation: 24005

If options is the only mechanism available to change figure size, then you'd do something like this to set & restore the options to whatever they were:

saved <- options(repr.plot.width=10, repr.plot.height=8)
ggplot(iris, aes(x = Sepal.Length, y= Sepal.Width)) + geom_point()
options(saved)

Upvotes: 1

user41871
user41871

Reputation:

Here you go:

library(repr)
options(repr.plot.width=10, repr.plot.height=8)
ggplot(iris, aes(x = Sepal.Length, y= Sepal.Width)) +
    geom_point()

Upvotes: 41

Related Questions