This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Saving high quality image in R

Hello all,

I am trying to save image in R with resolution= 300 in tiff or png formate

I have this code, but for some reason, the image is not saved in the directory

tiff("test.tiff", units="cm", width=5, height=7, res=300, pointsize=6)
ggplot(data=a, aes(x=BIN_START, y=1)) +
facet_grid(CHROM ~ ., switch='y') +
geom_tile(aes(fill=SNP_COUNT)) +
theme(axis.text.x=element_text(angle=0, size=12),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
strip.text.y = element_text(size= 12, angle = 180)) +
scale_x_continuous(breaks = c(0,10,20,30,40,50))+
xlab("Position (Mbp)")+ labs(fill = "Number of SNPs")+
scale_fill_gradientn(colours = viridis(5), breaks=seq(min(a$SNP_COUNT),max(a$SNP_COUNT,
(max(a$SNP_COUNT)-min(a$SNP_COUNT))/4))
dev.off()

Does anyone have an idea why the image is not saved? it should work

r

2 answers

I don't know why your code wouldn't work, but I would use ggsave to save ggplot images. So, in this case, I would do:

g <- ggplot(data=a, aes(x=BIN_START, y=1)) +
    facet_grid(CHROM ~ ., switch='y') +
    geom_tile(aes(fill=SNP_COUNT)) +
    theme(axis.text.x=element_text(angle=0, size=12),
          axis.title.y=element_blank(),
          axis.text.y=element_blank(),
          axis.ticks.y=element_blank(),
          strip.text.y = element_text(size= 12, angle = 180)) +
    scale_x_continuous(breaks = c(0,10,20,30,40,50))+
    xlab("Position (Mbp)")+ labs(fill = "Number of SNPs")+
    scale_fill_gradientn(colours = viridis(5), breaks=seq(min(a$SNP_COUNT),max(a$SNP_COUNT,
             (max(a$SNP_COUNT)-min(a$SNP_COUNT))/4))
ggsave("test.tiff", g, width=5, height=7, units="cm", dpi=300)

I'm not sure you can set the pointsize in the ggsave call, and should change it in theme if you need to.

Controlling the width and height solved the problem:

tiff("test.tiff", units="cm", width=20, height=15, res=300, pointsize=6)

For flexibility (in re-working the image) and overall better visual quality, you should save all figures as PDF. TIFF is pixel-based, whereas PDF is vector-based.

Log in to answer this question.