Patrick Balada
Patrick Balada

Reputation: 1450

How to remove vertical white lines when using ggsave in R?

I am currently on R 3.5.3 and my os is osx mojave. When I save a histogram in R using the ggsave-function, I get these very fine vertically oriented white lines. They don't show up in my R-Viewer but only in preview and vs code (and probably other viewers). Please see the screenshot below. A reproducible example would be the following.

library(dplyr)
library(ggsave)

df <- data.frame(values = sample (c(1:20), size = 1000, replace = T))

histogram <- df %>%
   ggplot(aes(x = values)) +
   geom_histogram(aes(y=..density..), alpha = 0.7, position = "identity", binwidth = 1, size = 0) +
   theme_minimal()

ggsave(histogram, file = "histogram.pdf")

Is there a way to change this behavior? After saving the figure, I would like to insert it into LaTex and make sure these white lines are gone.

enter image description here

Upvotes: 2

Views: 1275

Answers (2)

dez93_2000
dez93_2000

Reputation: 1875

Try increasing the dpi. I had this with a map and doubled the dpi to 600 and they disappeared.

Upvotes: 0

tom
tom

Reputation: 725

The PDF format is creating these white lines when bars are overlapping. You may be interested to use the PNG format to save the plot as it can be seen in the viewer.

Otherwise you may keep the PDF format and revise your plot aesthetics by setting color and fill with the same color. You would also need to adjust the alpha.

library(dplyr) library(ggsave)

df <- data.frame(values = sample (c(1:20), size = 1000, replace = T))

histogram <- df %>%
    ggplot(aes(x = values)) +
    geom_histogram(aes(y=..density..), alpha = 1,color = "dark grey", fill = "dark grey", position = "identity", binwidth = 1, size = 0) +
    theme_minimal()

ggsave(histogram, file = "histogram.pdf")

Upvotes: 3

Related Questions