【问题标题】:ggplot2 is cutting out the plot's marginsggplot2 正在削减情节的边距
【发布时间】:2021-04-08 21:44:13
【问题描述】:

我在base Rggplot2 中绘制密度。

当我使用base R 时,情节正常,但在ggplot2 中,边距被剪掉了。

这是base R中的情节:

library(tidyverse)
library(mvtnorm)
library(reshape2)
#> 
#> Attaching package: 'reshape2'
#> The following object is masked from 'package:tidyr':
#> 
#>     smiths

sd <- 1 / 2
# sigma
s1 <- sd^2

mu1 <- c(0, 0)
sigma1 <- matrix(c(s1^2, 0, 0, s1^2), nrow = 2)

# first two vectors
x.points <- seq(-3, 3, length.out = 100)
y.points <- seq(-3, 3, length.out = 100)

# the third vector is a density
z <- matrix(0, nrow = 100, ncol = 100)
z[] <- dmvnorm(expand.grid(x.points, y.points), mean = mu1, sigma = sigma1)

contour(x.points, y.points, z, xlim = range(-3, 3), ylim = c(-3, 3), nlevels = 5, drawlabels = TRUE)

这是ggplot2中的情节:

df <- reshape2::melt(z)
df <- transform(
  df,
  x = x.points[Var1],
  y = y.points[Var2]
)

ggplot(df, aes(x, y)) +
  geom_contour(aes(z = value)) +
    xlim(-3,3) +
    ylim(-3,3) +
    theme_classic() 

reprex package (v0.3.0) 于 2021-04-08 创建

当我开始制作情节时,两个情节都表现得很好。我正在运行par(pty = "s")(不幸的是,如果我在reprex() 中包含par 命令,则会出现问题并且没有情节。)par 命令正在工作,并为我提供了base R 的平方图和ggplot2。然后我在ggplot2 图中添加了一条线和一些点:

points <- data.frame(
  x = c(0, 1, 1.5, 1, 0),
  y = c(-3, -2.5, 0, 2.5, 3)
)
ggplot(df, aes(x, y)) +
  geom_contour(aes(z = value)) +
    xlim(-3,3) +
    ylim(-3,3) +
    geom_path(mapping = aes(x=points[,1], y=points[,2]), points) +
    geom_point(mapping = aes(x=points[,1], y=points[,2]), points) +
    theme_classic() 

添加点后,ggplot2 绘图开始切割边距。

我尝试在this advice 之后添加dev.new(width=10, height=10),但当然,它只是打开了一个新的图形设计,此外,边距也被削减了。我还尝试使用dev.off() 重置绘图设备,并重新启动 R 会话。

【问题讨论】:

  • 作为一般评论; ggplot2 不响应基本 R parmfrow 函数。
  • 谢谢你,知道这很有帮助。

标签: r ggplot2


【解决方案1】:

问题是经典主题theme_classic():看起来无论情节类型如何,theme_classic() 只会在情节周围绘制方框的两侧。

library(tidyverse)
library(mvtnorm)
library(reshape2)
#> 
#> Attaching package: 'reshape2'
#> The following object is masked from 'package:tidyr':
#> 
#>     smiths

sd <- 1 / 2
# sigma
s1 <- sd^2

mu1 <- c(0, 0)
sigma1 <- matrix(c(s1^2, 0, 0, s1^2), nrow = 2)

# first two vectors
x.points <- seq(-3, 3, length.out = 100)
y.points <- seq(-3, 3, length.out = 100)

# the third vector is a density
z <- matrix(0, nrow = 100, ncol = 100)
z[] <- dmvnorm(expand.grid(x.points, y.points), mean = mu1, sigma = sigma1)

df <- reshape2::melt(z)
df <- transform(
  df,
  x = x.points[Var1],
  y = y.points[Var2]
)

ggplot(df, aes(x, y)) +
  geom_contour(aes(z = value)) +
    xlim(-3,3) +
    ylim(-3,3) +
    theme_bw() 

reprex package (v0.3.0) 于 2021-04-08 创建

【讨论】:

    猜你喜欢
    • 2021-02-02
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多