Plotting Examples – Scatter plot and histogram in R

A friend asked me to write some code which produces a bimodal and a monomodal distribution and I thought someone might find the code useful.

My friend needed two plots without annotation: one showing a scatterplot with a cloud of dots in the center of the coordinate system and another plot with two clusters of dots that are close to the extremes of the x-axis. I wrote some code showing these two graphs but have continued to dabble with the code to also include histograms with their density function plotted as a line onto the bars.
So, here is the code and the plots it produces.

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 ############################################################### ### R script "Plotting examples" ############################################################### ### --- Prepare data # Remove all lists from the current workspace rm(list=ls(all=T))   # set graphic's parameters: four plots in one window par(mfrow = c(2, 2))   # generate data: bimodal distribution x1a <- rnorm(50, 0, 2) # create vector x1a with length 50, mean = 0 and sd = 2 x1b <- rnorm(50, 10, 2) # create vector x1b with length 50, mean = 10 and sd = 2 y1 <- rnorm(100, 20, 20) # create vector y1 with length 100, mean = 20 and sd = 20 # combine vectors into a table & convert table into a data frame tb1 <- as.data.frame(cbind(c(x1a, x1b), y1)) colnames(tb1) <- c("x.coordinate", "y.coordinate") # add column names tb1 <- tb1[tb1[, 1] >= 0 & tb1[, 1] <=10, ] # remove rows where x is smaller or equal to 0 greater or eqal to 10   # generate scatterplot plot(tb1, # plot data in tb1 xlim = c(0, 10), # x axis range (from 0 to 10) axes = F, # do not plot the axis xlab = "", # do not add an x-axis label ylab = "", # do not add an y-axis label pch = 19) # add filled dots (instead of empty dots) box() # plot a box around the distribution   # histogram of the first column of tb1 hist(tb1[, 1], xlim = c(0, 10), axes = F, xlab = "", ylab = "", breaks = 10, main = "", col = "lightgrey", freq = F) box() tb1.d <- density(tb1[, 1]) lines(tb1.d, col = "red", lty = 3)   # generate data: monomodal distribution x2 <- rnorm(50, 10, 2) y2 <- rnorm(50, 10, 2) # combine vectors into a table & convert table into a data frame tb2 <- as.data.frame(cbind(x2, y2)) colnames(tb2) <- c("x.coordinate", "y.coordinate") # add column names   # generate scatterplot of tb2 plot(tb2, xlim = c(5, 15), ylim = c(5, 15), axes = F, xlab = "", ylab = "", pch = 19) box()   # generate histogram of tb2 hist(tb2\$x.coordinate, axes = F, xlab = "", ylab = "", main = "", col = "lightgreen", freq = F) box() tb2.d <- density(tb2\$x.coordinate) lines(tb2.d, col = "black", lty = 1, lwd = 1)   # restore original graphic's parameters par(mfrow = c(1, 1)) 