# How to do this graph using R

April 26, 2010
By

(This article was first published on stattler.com - R, and kindly contributed to R-bloggers)

I am showing three examples that will help an average R user to create beautiful graphs. The interesting (may be useful) parts of these examples are the use of some very smart but tricky functions to, for example, add a Greek symbol on a plot, add a title to a plot with some mathematical symbols.

I am showing three examples that will help an average R user to create beautiful graphs. The interesting (may be useful) parts of these examples are the use of some very smart but tricky functions to, for example, add a Greek symbol on a plot, add a title to a plot with some mathematical symbols. In these examples I used expression and paste functions repeatedly. For more examples please see this site.

### EXAMPLE 1: Gamma density with scale parameter =1 and various shape parameter

x <- seq(0, 30, length=300)
hx <- dgamma(x, shape=1, scale=1)

gshape <- c(2, 5, 10, 15)
colors <- c("red", "blue", "darkgreen", "gold")

plot(x, hx, type="n", lty=2, lwd=2, xlab="x", ylab=expression(f(x)), main=expression(theta == 1), ylim=c(0,0.4), frame.plot=F)

for (i in 1:4){
lines(x, dgamma(x,shape=gshape[i], scale=1), lwd=2, col=colors[i])
}

# Inserting mathematical expressions

text(3.5,.35 , expression(paste(alpha==2)))
text(6.5,.18 , expression(paste(alpha==5)))
text(11.5,.13 , expression(paste(alpha==10)))
text(23,.05 , expression(paste(alpha==15)))

### EXAMPLE 2: Barplot for Poisson distribution

# Generating Poisson random numbers with rates 1, 2, 3, and 4
# and drawing the histograms and arranging them on a 2 x 2 matrix

par(mfrow=c(2,2))
lambda <- 1:4
x <- 0:10

for (i in lambda)
{
x1 <- dpois(x, lambda[i])
barplot(x1, names.arg=c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), ylab=expression(P(x)), ylim=c(0,.4), col="lightgreen")
title(main = substitute(lambda == i,list(i=i)))
}

### EXAMPLE 3: Binomial probability plots (line diagram)

# Binomial probability plot with vertical lines

par(mfrow=c(2,2))
n <- 10
p <- c(0.1, 0.25, 0.5, 0.8)
x <- 0:10
for (i in 1:4)
{
x1 <- dbinom(x, n, p[i])
plot(x1, type="h", xlab="x", ylab=expression(P(x)),
ylim=c(0,.4),lwd=2, col="red")
j <- p[i]
title(main = substitute(p == j,list(j=j)))
}

Thank you.

Category: