Plotting multiple data series in #R using #Lattice

The following code is a short tutorial to make a simple chart using lattice package. I use the electricity consumption data from US Dept.of Energy. To make a simple plot using R is a learning curve. It is straight forward, so you will be able to use it, once you get the basic properties.

Loading package and data

  1. loading library
  2. loading data (30 rows and 6 columns)
  3. example on subsetting data, only read row 1 to 29, and excluding line 30.
require("lattice")
## Loading required package: lattice
data <- read.csv("enconsump.csv")
mydata <- data[c(1:29), ]

First plot: Simple xyplot using the available data

  1. plotting
  2. x axis=Country column
  3. y axis=Year column (2007-2011)
  4. point style (pch)=16
  5. legend by auto key
  6. x and y is the coordinate of the legend
xyplot(mydata$Country ~ mydata$X2007 + mydata$X2008 + mydata$X2009 + mydata$X2010 + 
    mydata$X2011, main = "Electricity consumption (2007-2011)", type = "p", 
    pch = 16, auto.key = list(x = 0.7, y = 0.8, text = c("2007", "2008", "2009", 
        "2010", "2011"), title = "Year"), ylab = "countries", xlab = "billion Kwh")

plot of chunk unnamed-chunk-2

Second plot: Simple plot using manually-entered data

  1. making plot from manually entered data
  2. making short time series of world's total electricity consumption
  3. main : setting chart title
  4. type="b" : type both point and line
  5. pch=16 : setting point type
  6. xaxt="n" : no axis label
  7. xlab : setting x axis label
  8. ylab : setting y axis label
  9. axis(1...: setting x tick label
total <- c(17149.41987, 17410.00845, 17316.83824, 18501.4416, 19298.53181)
plot(total, main = "World's total electricity consumption", type = "b", pch = 16, 
    xaxt = "n", xlab = "Years", ylab = "energy consumption, in billion Kwh")
axis(1, at = 1:5, labels = c("2007", "2008", "2009", "2010", "2011"))

plot of chunk unnamed-chunk-3

#References: Energy Report-US Dept of Energy