Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R plot: size and resolution

Tags:

plot

r

png

I have stacked into the question: I need to plot the image with DPI=1200 and specific print size.

By default the png looks ok... enter image description here

png("test.png",width=3.25,height=3.25,units="in",res=1200) par(mar=c(5,5,2,2),xaxs = "i",yaxs = "i",cex.axis=1.3,cex.lab=1.4) plot(perf,avg="vertical",spread.estimate="stddev",col="black",lty=3, lwd=3) dev.off() 

But when I apply this code, the image became really terrible it's not scaling (fit) to the size that is needed. What did I miss? How to "fit" the image to the plot?

enter image description here,

like image 444
chupvl Avatar asked Dec 06 '11 11:12

chupvl


People also ask

How do I change the resolution of a plot in R?

In base R, we can save a plot as a png and pass the resolution in the same stage. The procedure to do this is creating the png image with resolution with res argument then creating the plot and using dev. off() to create the file.

What is the par function in R?

The par() function is used to set or query graphical parameters. We can divide the frame into the desired grid, add a margin to the plot or change the background color of the frame by using the par() function. We can use the par() function in R to create multiple plots at once.


1 Answers

A reproducible example:

the_plot <- function() {   x <- seq(0, 1, length.out = 100)   y <- pbeta(x, 1, 10)   plot(     x,     y,     xlab = "False Positive Rate",     ylab = "Average true positive rate",     type = "l"   ) } 

James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

png(   "test.png",   width     = 3.25,   height    = 3.25,   units     = "in",   res       = 1200,   pointsize = 4 ) par(   mar      = c(5, 5, 2, 2),   xaxs     = "i",   yaxs     = "i",   cex.axis = 2,   cex.lab  = 2 ) the_plot() dev.off() 

Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

library(ggplot2)  ggplot_alternative <- function() {   the_data <- data.frame(     x <- seq(0, 1, length.out = 100),     y = pbeta(x, 1, 10)   )  ggplot(the_data, aes(x, y)) +     geom_line() +     xlab("False Positive Rate") +     ylab("Average true positive rate") +     coord_cartesian(0:1, 0:1) }  ggsave(   "ggtest.png",   ggplot_alternative(),   width = 3.25,   height = 3.25,   dpi = 1200 ) 
like image 73
Richie Cotton Avatar answered Sep 28 '22 10:09

Richie Cotton