Plotting functions of a variable in a dataset

Sometimes, we might wish to visualize the effect of applying a mathematical function to a set of values, instead of the original variable itself. In this recipe, we will learn a simple method to plot functions of variables.

Getting ready

We will use the base graphics library for this recipe, so all you need to do is run the recipe at the R prompt. It is good practice to save your code as a script for use again later.

How to do it...

Let's say we want to plot the difference in rainfall between Tokyo and London. We can do this just by passing the correct expression to the plot() function:

rain <- read.csv("cityrain.csv")

plot(rain$Berlin-rain$London,type="l",lwd=2,
xaxt="n",col="blue",
xlab="Month",ylab="Difference in Rainfall (mm)",
main="Difference in Rainfall between Berlin and London (Berlin-London)")

axis(1,at=1:length(rain$Month),labels=rain$Month)

abline(h=0,col="red")
How to do it...

How it works...

So, plotting a function of a variable is as simple as passing an expression to the plot() function. In the example, the function consisted of two variables in the dataset. We can also plot transformations applied to any one variable.

There's more...

As another simple example, let's see how we can plot a polynomial function of a set of numbers:

x<-1:100
y<-x^3-6*x^2+5*x+10
plot(y~x,type="l",main=expression(f(x)==x^3-6*x^2+5*x+10))
There's more...

In the preceding example, we defined y as a polynomial function of a vector of the numbers 1 to 100 and then plotted it using the plot() function. Note that we used the expression() function to format the title of the graph. By using expression(), we can get the power values as superscripts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.61.243