Creating sparklines

Sparklines are small and simple line graphs, useful to summarize trend data in a small space. The word sparklines was coined by Prof. Edward Tufte. In this recipe, we will learn how to make sparklines using a basic plot() function.

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 represent our city rainfall data in the form of sparklines:

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

par(mfrow=c(4,1),mar=c(5,7,4,2),omi=c(0.2,2,0.2,2))

for(i in 2:5)
{
    plot(rain[,i],ann=FALSE,axes=FALSE,type="l",
    col="gray",lwd=2)

    mtext(side=2,at=mean(rain[,i]),names(rain[i]),
    las=2,col="black")

    mtext(side=4,at=mean(rain[,i]),mean(rain[i]),
    las=2,col="black")

    points(which.min(rain[,i]),min(rain[,i]),pch=19,col="blue")
    points(which.max(rain[,i]),max(rain[,i]),pch=19,col="red")
}
How to do it...

How it works...

The key feature of sparklines is to show the trend in the data with just one line without any axis annotations. In the example, we have shown the trend with a gray line. The minimum and maximum values for each line is represented by blue and red dots, respectively, while the mean value is displayed on the right margin.

As sparklines have to be very small graphics, we first set the margins such that the plot area is small and the outer margins are large. We did this by setting the outer margins in inches using the omi argument of the par() function. Depending on the dimensions of the plot, sometimes R produces an error that says that the figure margins are too large, and does not draw the graph. In this case, we need to try lower values for the margins. Note that we also set up a 4 x 1 layout with the mfrow argument.

Next, we set up a for loop to draw a sparkline for each of the four cities. We drew the line with the plot() command, setting both annotations, ann and axes, to false. Then, we used the mtext() function to place the name of the city and the mean value of rainfall to the left and right of the line, respectively. Finally, we plotted the minimum and maximum values using the points() command. Note that we used the which.min() and which.max() functions to get the indices of the minimum and maximum values, respectively, and used them as the x value for the points() function calls.

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

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