【问题标题】:R - Changing ggplot plot size in jupyterR - 在 jupyter 中更改 ggplot 绘图大小
【发布时间】:2017-08-03 00:54:06
【问题描述】:

在 jupyter notebook 中使用 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 中,绘图大小通常不是问题。

【问题讨论】:

    标签: r ggplot2 jupyter


    【解决方案1】:

    给你:

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

    【讨论】:

    • library(repr) 部分对我来说是不必要的
    • OP已经设置了通用设置。如何将第二个绘图设置为自定义尺寸?
    • 这会改变所有地块的设置?!对于不同的地块,我该如何以不同的方式执行此操作?
    【解决方案2】:

    我找到了另一种解决方案,即使您在函数或循环中绘制绘图,也可以设置绘图大小:

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

    【讨论】:

    • 你最后少了一个括号,应该是print(pl, vp=grid::viewport(width=unit(10, 'inch'), height=unit(8, 'inch')))
    【解决方案3】:

    如果 options 是唯一可用于更改图形大小的机制,那么您可以执行以下操作来设置和恢复选项:

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

    【讨论】:

      【解决方案4】:

      不涉及使用外部包的解决方案是这样的。

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

      例如,只需将 fig(10, 4) 放在生成绘图的单元格中,绘图就会相应缩放

      来源:https://www.kaggle.com/getting-started/105201

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-17
        • 2017-08-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-20
        • 2011-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多