Book Image

R Graphs Cookbook Second Edition

Book Image

R Graphs Cookbook Second Edition

Overview of this book

Table of Contents (22 chapters)
R Graphs Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

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 it works...

The key...