Why using R for plotting

Basic plot example

'data.frame':   19 obs. of  2 variables:
 $ temperature: num  0 20 40 60 80 100 120 140 160 180 ...
 $ pressure   : num  0.0002 0.0012 0.006 0.03 0.09 0.27 0.75 1.85 4.2 8.8 ...

Labels and Axes


Symbols, colors, and lines

Plot symbols

Use the pch= option to specify symbols to use when plotting points. For symbols 21 through 25, specify border color (col=) and fill color (bg=).

Default color palette in R

palette("default") # you'll only need this line if you've previously changed the palette from the default
[1] "black"   "red"     "green3"  "blue"    "cyan"    "magenta" "yellow"  "gray"   

Line types (lty= )

#Solid line (by default)
plot(1:10, 1:10, type="l")
#Use dashed line type
plot(1:10, 1:10, type="l", lty=2)
#Change line width
plot(1:10, 1:10, type="l", lty=2, lwd=3)

Example: plot points with formatting

plot(pressure, type="p")

plot(pressure, type="p", pch=8, cex=0.8, col="red")

Example: Line graph with formatting

plot(pressure, type="l", lty=3, lwd=2, col="blue")

Example: Add title and text

plot(pressure, main="Relation")

text(150, 200, label="p-value = 0.05")

Plot for multiple groups

data(iris) #load iris data
pch.vec <- c(2,8,21)[iris$Species]
col.vec <- c(2,3,6)[iris$Species]
plot(iris$Sepal.Length, iris$Sepal.Width, col=col.vec, pch=pch.vec, xlab="sepal.length", ylab="sepal.width", main="iris")
legend("topleft", pch=c(2,8,21), col=c(2,3,6), legend=unique(iris$Species), cex=0.8)

Beyond simple graphs: ggplot2

Build-in R plotting vs. ggplot2

Need help? Try Stackoverflow: https://stackoverflow.com/tags/ggplot2.
plot(diamonds$carat, diamonds$price, col=diamonds$color, pch=as.numeric(diamonds$cut))

ggplot(diamonds, aes(carat, price, col=color, shape=cut)) + geom_point()

Scatter plot

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, shape=Species, colour=Species)) + geom_point()

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, shape=Species, colour=Species)) + geom_point() +
  scale_color_brewer(palette="Dark2") + 
  scale_shape_manual(values=c(2,8,0)) +
  labs(x="Length", y="Width", title="Sepal Length vs. Width") +
  theme(plot.title = element_text(hjust=0.5))

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, shape=Species, colour=Species)) + geom_point() +
  geom_smooth(method=lm,, se=FALSE)