I recently encountered several cases where the ggplot
produced jagged lines. In the following example, I generate dense time-course data with the package fda
and draw two line plots. The first plot gives the black line and the other plot displays the same line except that we use different colors to denote the signs of the values. In the end, I export the plots as eps files and open them in Adobe 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)
In the screenshots which display the zoomed-in line, we observe that the line in the first plot is smooth, while the line in the second plot is jagged. How can I fix the problem?
Here's my system info:
# R version 4.1.1 (2021-08-10)
# Platform: x86_64-w64-mingw32/x64 (64-bit)
# Running under: Windows 10 x64 (build 22000)
Note: My goal is to generate an eps/pdf file of something like the second plot from R. Other methods that achieve the same goal are appreciated.
CodePudding user response:
You should add lineend = "round"
to your geom_line
ggplot(dat)
geom_line(aes(x = t, y = y, color = pos, group = 1), lineend = "round")
theme_bw()
theme(panel.grid = element_blank())
It will look nice via export -> save as PDF
and windows() -> save as...
too.
An example (2400%):