logo

Drawing Graphs in R 📂R

Drawing Graphs in R

Overview

R has the advantage of making the representation of graphs very easy compared to other languages.

When compared with other statistical packages, while easy drawings might be faster in those packages, R tends to become more convenient as the need for detailed expressions increases.

Of course, R is not only for graphics, but since it is a very big advantage, it is good to practice to handle it freely.

Code

set.seed(150421)
x<-1:10
y<-rnorm(10,5)
z<-rexp(10)

win.graph(4,4)

plot(x,y,main="주제목",sub="부제목",xlab="x-axis",ylab="y축")
win.graph(8,4)
par(mfrow=c(1,2))
plot(x,y,main="왼쪽 한 칸만 사용한 상태")

plot()

1.png

This is the most basic function for drawing graphs, taking the first argument as the $x$ axis and the second argument as the $y$ axis to draw a 2-dimensional graph. Main options include:

  • main: Takes a string to set the main title of the graph. sub adds a subtitle but isn’t used much.
  • xlab, ylab (x label, y label): Takes a string to set the names of the axes.
  • xlim, ylim (x limit, y limit): Takes a $2$ vector to adjust the limits that the axes are displayed.
  • type: Sets the type of graph. By default, it plots points, and by entering type='l', a line graph can be drawn.
  • asp (aspect): adjusts the scale between the $x$ axis and the $y$ axis. If true, the ratio is matched exactly; if false, it’s automatically decided for each axis.

win.graph()

5B72CD4C0.png

win.graph() is a function that opens a new window for drawing graphs, mainly used to adjust the size of the graph consistently. Entering two numbers adjusts the width and height.

par(mfrow=c(1,2))

2.png

This function splits the window in which graphs will be drawn, making it useful for spreading out and comparing various graphs.

par(new=TRUE)

Functions including plot() overwrite existing graphs when drawing. Although not often used, entering par(new=TRUE) allows drawing a new graph while leaving the existing graph unchanged.