Book Image

R Graph Essentials

Book Image

R Graph Essentials

Overview of this book

This book is targeted at R programmers who want to learn the graphing capabilities of R. This book will presume that you have working knowledge of R.
Table of Contents (6 chapters)
5
Index

Passing parameter values to titles and labels

In the next example, we pass parameter values to the title and the axis labels and create the labels using the paste() command. This technique can be useful for creating titles and labelling automatically from within an R program (usually called a script). Let's create a set of values first using the following commands:

k <- 9
min <- 3
max <- 25
name <- "Mary"

Before we start, try the following code:

paste(name, "'s Mark", sep = "")

You will get the following output:

[1] "Mary's Mark"

The content of the variable name (Mary) was pasted together with the text 's Mark. Each element of the text is separated by commas, while the argument sep = "" ensures that there are no breaks between the variable and the text. That's the way the paste() function works.

Let's start again and enhance the plot. Let's create our plot using colors taken from the Hexadecimal Color Chart. The commands to be used are as follows:

plot(X, Y, type="o", col="#669966", xlab = paste(name, "'s Mark", sep = ""), ylab = paste("Marks from ", min, " to ", max,  sep = "")) 

Now let's create a title:

title(main = paste("Plot ", k, " for ", name, sep = ""), font.main = 2, col.main = "#CC6600")

The following is our graph, with the appropriate labels and title:

Passing parameter values to titles and labels

The title() command is one way of creating a title. However, by using the main argument, you can also create a title within the plot() command (as shown in the next example). In the following example, we pass the same parameter values to the title and the axis labels. Enter the following syntax on the command line:

plot(X, Y, type = "o", col = "red", main = paste("Plot ", k, " for ", name, sep = ""), pch = 16, cex = 1.4, font.main = 2, col.main = "blue", xlab = paste(name, "'s Mark", sep = ""), ylab = paste("Marks from ", min, " to ", max,  sep = "")) 

As in the previous example, the cex parameter controls the symbol size (the default value is 1). The resulting graph is as follows:

Passing parameter values to titles and labels

Indeed, we have the correct axis labels and title. You can check out the parameters pch and lty for yourselves.