ggplot 在特定情况下生成 jagged/broken 行

ggplot generates jagged/broken lines in specific cases

我最近遇到了几个 ggplot 产生锯齿线的案例。在下面的示例中,我使用包 fda 生成密集的时间过程数据并绘制两条线图。第一个图给出黑线,另一个图显示相同的线,只是我们使用不同的颜色来表示值的符号。最后,我将绘图导出为 eps 文件并在 Adob​​e Illustrator 中打开它们。

# install.packages("fda")
# dir.create("tmp")

library(dplyr)
library(tidyr)
library(ggplot2)
library(fda)

times_sparse <- seq(0, 10, 0.5)
times <- seq(0, 10, 0.02)

basis <- create.bspline.basis(
  rangeval = c(0, 10), norder = 4,
  breaks = times_sparse
)
nbasis <- basis$nbasis

set.seed(2501)
coeff <- rnorm(nbasis, sd = 0.1)

y <- eval.fd(times, fd(coeff, basis)) |> as.numeric()

dat <- data.frame(t = times, y = y) |>
  mutate(pos = factor((y > 0) * 1, levels = c(1, 0)))

### first plot: 1 colors, smooth lines
ggplot(dat) +
  geom_line(aes(x = t, y = y)) +
  theme_bw() +
  theme(panel.grid = element_blank())
# ggsave("tmp/line1a.eps", device = "eps",
#        width = 6, height = 6)

### second plot: 2 colors, jagged lines
ggplot(dat) +
  geom_line(aes(x = t, y = y, color = pos, group = 1)) +
  theme_bw() +
  theme(panel.grid = element_blank())
# ggsave("tmp/line1b.eps", device = "eps",
#        width = 6, height = 6)

在显示放大线的屏幕截图中,我们观察到第一个图中的线是平滑的,而第二个图中的线是锯齿状的。我该如何解决这个问题?

这是我的系统信息:

# R version 4.1.1 (2021-08-10)
# Platform: x86_64-w64-mingw32/x64 (64-bit)
# Running under: Windows 10 x64 (build 22000)

注意:我的目标是生成一个 eps/pdf 文件,类似于 R 中的第二个图。赞赏实现相同目标的其他方法。

您应该将 lineend = "round" 添加到您的 geom_line

ggplot(dat) +
     geom_line(aes(x = t, y = y, color = pos, group = 1), lineend = "round") +
     theme_bw() +
     theme(panel.grid = element_blank())

通过 export -> save as PDFwindows() -> save as... 看起来也不错。

一个例子(2400%):