We look at simple plotting with base functions (without using any packages). R has very good visualization package called ggplot2. Tutorial for that is on another page.
Orig <- read.csv("https://nmimoto.github.io/datasets/plants.csv")
# load the dataset directly from website.
dim(Orig) # n=32. Ther are 3 columns
## [1] 32 3
## [1] "Cost" "MWatts" "Date"
## Cost MWatts Date
## 1 345.39 514 67.92
## 2 460.05 687 68.58
## 3 452.99 1065 67.33
## 4 443.22 1065 67.33
## 5 652.32 1065 68.00
## 6 642.23 1065 68.00
Note that MWatts is on x-axis.
Let’s load lynx.csv from my website.
Orig <- read.csv("https://nmimoto.github.io/datasets/lynx.csv")
# load the dataset directly from website.
head(Orig) # the data only has one column called "Lynx"
## Lynx
## 1 269
## 2 321
## 3 585
## 4 871
## 5 1475
## 6 2821
## [1] 114 1
plot(X) # scatter plot is the default for plot()
plot(X, type="p") # type="p" gives the same scatter plot
Googling something like “R how to change line type” is the best bet. You can also look at R documentation by command:
You can add horizontal and vertical lines to existing plot.
Orig <- read.csv("https://nmimoto.github.io/datasets/lynx.csv")
X = Orig$Lynx
plot(X, type="l")
M = mean(X)
abline(h=M, col="red") # h for horizontal
abline(v=30, col="blue") # v for vertical
You can also draw line with intercept and slope.
Orig2 <- read.csv("https://nmimoto.github.io/datasets/wine.csv")
# load in wine.csv from webpage
head(Orig2) # has 1 column called "wine"
## wine
## 1 464
## 2 675
## 3 703
## 4 887
## 5 1139
## 6 1077
## [1] 142 1
Note that lines() uses type=“l” as default. You can change it by usint type= command if you need to.
Note that lines() use uses the plot that is already drawn by plot(). So which one to plot first does matter. You can specify the range of the plot in plot().
plot(X, type="l", xlim=c(0,200), ylim=c(0, 8000)) # plot X with more range
lines(Y, col="red") # overlay Y
You can plot more than 1 plot on a same page. Here’s horizontal stack.
Vertical stack.
As 2 by 2 panel.
layout(matrix(1:4, 2, 2)) # set up layout as (2x2) matrix
plot(X, type="l")
plot(Y, type="l")
plot(X, type="l")
plot(Y, type="l")