Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anti-aliasing for ggplot exports

Tags:

Is it possible to get fine anti-aliasing for exported ggplot plots? I have tried the Cairo package as well as few different devices, but they all seems to have jagged edges.

library(ggplot2)
library(Cairo)

p <- ggplot(data.frame(x=1:5,y=1:5),aes(x=x,y=y))+
  geom_text(aes(2.5,2.5),label="Brown Fox bla bla..",size=5)+
  labs(x=NULL,y=NULL)+
  theme_bw()+
  theme(plot.background=element_blank(),
        plot.margin = margin(c(0,0,0,0)),
        axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.line = element_blank(),
        panel.grid = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank())

png("test-nocairo.png",height=2,width=6,units="cm",res=300)
print(p)
dev.off()

png("test-cairo.png",height=2,width=6,units="cm",res=300,type="cairo")
print(p)
dev.off()

tiff("test-cairo.tiff",height=2,width=6,units="cm",res=300,type="cairo")
print(p)
dev.off()

ggsave("test-ggsave.png",height=2,width=6,units="cm",dpi=300,type="cairo")

png-nocairo PNG no cairo

png-cairo PNG cairo

tiff-cairo TIFF cairo

png-ggsave-cairo PNG ggsave cairo

For my purpose, it is important that the images are PNG or TIFF (lossless) at 300dpi. I am aware that I can export to a vector format (SVG,PDF etc) and then convert to PNG/TIFF using another program, but that is obviously extra work. I am curious if there are any solutions in R that I am overlooking.

photoshop

For reference, above is the quality of rendering from photoshop. PNG Arial 14pt.

like image 863
rmf Avatar asked Sep 02 '17 12:09

rmf


1 Answers

Ok. I may have stumbled upon something here. When I use annotate rather than geom_text, the cairo anti-aliasing seems to work.

p <- ggplot(data.frame(x=1:5,y=1:5),aes(x=x,y=y))+
  annotate("text",x=2.5,y=2.5,label="Brown Fox bla bla..",size=5)+
  labs(x=NULL,y=NULL)+
  theme_bw()+
  theme(plot.background=element_blank(),
        plot.margin = margin(c(0,0,0,0)),
        axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.line = element_blank(),
        panel.grid = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank())

png("test-annotate-cairo.png",height=2,width=6,units="cm",res=300,type="cairo")
print(p)
dev.off()

png-annotate-cairo

So, it seems like geom_text is overplotting the same text which might be the issue. I thought this overplotting thing was fixed at some point. I think there is still room for improvement with the anti-aliasing, but this is much better than before.

like image 179
rmf Avatar answered Oct 04 '22 21:10

rmf