R - 在jupyter中更改ggplot图的大小

29
在Jupyter笔记本中使用R,首先我会设置通用的绘图大小。其次,我想用不同的尺寸绘制单个图。
## 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?

如您所见,我想将第二个图(仅限第二个图)更改为10X8。我该怎么做?

抱歉可能问了一个愚蠢的问题,因为在Rstudio中通常不会出现绘图大小的问题。

4个回答

40

给你:

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

9
library(repr) 这部分对我来说是不必要的。 - eddi
OP已经设置了通用设置。如何将第二个绘图设置为自定义尺寸? - shiv_90
这会更改所有图的设置?!我怎样才能为不同的图以不同的方式进行设置呢? - mah65

4

我找到了另一种解决方案,可以在函数或循环中制作图表时设置图表大小:

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')))

1
你漏掉了一个右括号,应该是 print(pl, vp=grid::viewport(width=unit(10, 'inch'), height=unit(8, 'inch'))). - TheSciGuy

2
一个不需要使用外部包的解决方案是这样的。
fig <- function(width, heigth){
 options(repr.plot.width = width, repr.plot.height = heigth)
 }

例如,在生成图形的单元格中只需输入fig(10, 4),即可按比例缩放绘图。
来源:https://www.kaggle.com/getting-started/105201

1
如果 options 是改变图形大小的唯一机制,那么您可以像这样设置和恢复选项以使其回到原来的状态:
saved <- options(repr.plot.width=10, repr.plot.height=8)
ggplot(iris, aes(x = Sepal.Length, y= Sepal.Width)) + geom_point()
options(saved)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接