R Basic Visualization

Easy Way to Plot

Ben
Engineer, GBC

資料整理完了,來畫圖吧~~~

The R Graphics Package

Package: graphics

  • basic function for graphics
  • Function List
library(help = "graphics")
  • 簡單
  • 可快速觀察資料
  • 自由度大,易調整版面

R basic graphic tools

  1. Simple Plots
  2. Add something to a plot
  3. Adjust
    • Graphical Elements
    • Figure Margins
    • Multiple Figure Environment
  4. Others
  5. Projects

Simple Plots

Simple Plots

Simple Plots

Object Class: data.frame or matrix or vector

Data: iris

Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.10 3.50 1.40 0.20 setosa
2 4.90 3.00 1.40 0.20 setosa
3 4.70 3.20 1.30 0.20 setosa
4 4.60 3.10 1.50 0.20 setosa
5 5.00 3.60 1.40 0.20 setosa
6 5.40 3.90 1.70 0.40 setosa
7 4.60 3.40 1.40 0.30 setosa
8 5.00 3.40 1.50 0.20 setosa
9 4.40 2.90 1.40 0.20 setosa
10 4.90 3.10 1.50 0.10 setosa
11 5.40 3.70 1.50 0.20 setosa
12 4.80 3.40 1.60 0.20 setosa
13 4.80 3.00 1.40 0.10 setosa
14 4.30 3.00 1.10 0.10 setosa
15 5.80 4.00 1.20 0.20 setosa
16 5.70 4.40 1.50 0.40 setosa
17 5.40 3.90 1.30 0.40 setosa
18 5.10 3.50 1.40 0.30 setosa
19 5.70 3.80 1.70 0.30 setosa
20 5.10 3.80 1.50 0.30 setosa
21 5.40 3.40 1.70 0.20 setosa
22 5.10 3.70 1.50 0.40 setosa
23 4.60 3.60 1.00 0.20 setosa
24 5.10 3.30 1.70 0.50 setosa
25 4.80 3.40 1.90 0.20 setosa
26 5.00 3.00 1.60 0.20 setosa
27 5.00 3.40 1.60 0.40 setosa
28 5.20 3.50 1.50 0.20 setosa
29 5.20 3.40 1.40 0.20 setosa
30 4.70 3.20 1.60 0.20 setosa
31 4.80 3.10 1.60 0.20 setosa
32 5.40 3.40 1.50 0.40 setosa
33 5.20 4.10 1.50 0.10 setosa
34 5.50 4.20 1.40 0.20 setosa
35 4.90 3.10 1.50 0.20 setosa
36 5.00 3.20 1.20 0.20 setosa
37 5.50 3.50 1.30 0.20 setosa
38 4.90 3.60 1.40 0.10 setosa
39 4.40 3.00 1.30 0.20 setosa
40 5.10 3.40 1.50 0.20 setosa
41 5.00 3.50 1.30 0.30 setosa
42 4.50 2.30 1.30 0.30 setosa
43 4.40 3.20 1.30 0.20 setosa
44 5.00 3.50 1.60 0.60 setosa
45 5.10 3.80 1.90 0.40 setosa
46 4.80 3.00 1.40 0.30 setosa
47 5.10 3.80 1.60 0.20 setosa
48 4.60 3.20 1.40 0.20 setosa
49 5.30 3.70 1.50 0.20 setosa
50 5.00 3.30 1.40 0.20 setosa
51 7.00 3.20 4.70 1.40 versicolor
52 6.40 3.20 4.50 1.50 versicolor
53 6.90 3.10 4.90 1.50 versicolor
54 5.50 2.30 4.00 1.30 versicolor
55 6.50 2.80 4.60 1.50 versicolor
56 5.70 2.80 4.50 1.30 versicolor
57 6.30 3.30 4.70 1.60 versicolor
58 4.90 2.40 3.30 1.00 versicolor
59 6.60 2.90 4.60 1.30 versicolor
60 5.20 2.70 3.90 1.40 versicolor
61 5.00 2.00 3.50 1.00 versicolor
62 5.90 3.00 4.20 1.50 versicolor
63 6.00 2.20 4.00 1.00 versicolor
64 6.10 2.90 4.70 1.40 versicolor
65 5.60 2.90 3.60 1.30 versicolor
66 6.70 3.10 4.40 1.40 versicolor
67 5.60 3.00 4.50 1.50 versicolor
68 5.80 2.70 4.10 1.00 versicolor
69 6.20 2.20 4.50 1.50 versicolor
70 5.60 2.50 3.90 1.10 versicolor
71 5.90 3.20 4.80 1.80 versicolor
72 6.10 2.80 4.00 1.30 versicolor
73 6.30 2.50 4.90 1.50 versicolor
74 6.10 2.80 4.70 1.20 versicolor
75 6.40 2.90 4.30 1.30 versicolor
76 6.60 3.00 4.40 1.40 versicolor
77 6.80 2.80 4.80 1.40 versicolor
78 6.70 3.00 5.00 1.70 versicolor
79 6.00 2.90 4.50 1.50 versicolor
80 5.70 2.60 3.50 1.00 versicolor
81 5.50 2.40 3.80 1.10 versicolor
82 5.50 2.40 3.70 1.00 versicolor
83 5.80 2.70 3.90 1.20 versicolor
84 6.00 2.70 5.10 1.60 versicolor
85 5.40 3.00 4.50 1.50 versicolor
86 6.00 3.40 4.50 1.60 versicolor
87 6.70 3.10 4.70 1.50 versicolor
88 6.30 2.30 4.40 1.30 versicolor
89 5.60 3.00 4.10 1.30 versicolor
90 5.50 2.50 4.00 1.30 versicolor
91 5.50 2.60 4.40 1.20 versicolor
92 6.10 3.00 4.60 1.40 versicolor
93 5.80 2.60 4.00 1.20 versicolor
94 5.00 2.30 3.30 1.00 versicolor
95 5.60 2.70 4.20 1.30 versicolor
96 5.70 3.00 4.20 1.20 versicolor
97 5.70 2.90 4.20 1.30 versicolor
98 6.20 2.90 4.30 1.30 versicolor
99 5.10 2.50 3.00 1.10 versicolor
100 5.70 2.80 4.10 1.30 versicolor
101 6.30 3.30 6.00 2.50 virginica
102 5.80 2.70 5.10 1.90 virginica
103 7.10 3.00 5.90 2.10 virginica
104 6.30 2.90 5.60 1.80 virginica
105 6.50 3.00 5.80 2.20 virginica
106 7.60 3.00 6.60 2.10 virginica
107 4.90 2.50 4.50 1.70 virginica
108 7.30 2.90 6.30 1.80 virginica
109 6.70 2.50 5.80 1.80 virginica
110 7.20 3.60 6.10 2.50 virginica
111 6.50 3.20 5.10 2.00 virginica
112 6.40 2.70 5.30 1.90 virginica
113 6.80 3.00 5.50 2.10 virginica
114 5.70 2.50 5.00 2.00 virginica
115 5.80 2.80 5.10 2.40 virginica
116 6.40 3.20 5.30 2.30 virginica
117 6.50 3.00 5.50 1.80 virginica
118 7.70 3.80 6.70 2.20 virginica
119 7.70 2.60 6.90 2.30 virginica
120 6.00 2.20 5.00 1.50 virginica
121 6.90 3.20 5.70 2.30 virginica
122 5.60 2.80 4.90 2.00 virginica
123 7.70 2.80 6.70 2.00 virginica
124 6.30 2.70 4.90 1.80 virginica
125 6.70 3.30 5.70 2.10 virginica
126 7.20 3.20 6.00 1.80 virginica
127 6.20 2.80 4.80 1.80 virginica
128 6.10 3.00 4.90 1.80 virginica
129 6.40 2.80 5.60 2.10 virginica
130 7.20 3.00 5.80 1.60 virginica
131 7.40 2.80 6.10 1.90 virginica
132 7.90 3.80 6.40 2.00 virginica
133 6.40 2.80 5.60 2.20 virginica
134 6.30 2.80 5.10 1.50 virginica
135 6.10 2.60 5.60 1.40 virginica
136 7.70 3.00 6.10 2.30 virginica
137 6.30 3.40 5.60 2.40 virginica
138 6.40 3.10 5.50 1.80 virginica
139 6.00 3.00 4.80 1.80 virginica
140 6.90 3.10 5.40 2.10 virginica
141 6.70 3.10 5.60 2.40 virginica
142 6.90 3.10 5.10 2.30 virginica
143 5.80 2.70 5.10 1.90 virginica
144 6.80 3.20 5.90 2.30 virginica
145 6.70 3.30 5.70 2.50 virginica
146 6.70 3.00 5.20 2.30 virginica
147 6.30 2.50 5.00 1.90 virginica
148 6.50 3.00 5.20 2.00 virginica
149 6.20 3.40 5.40 2.30 virginica
150 5.90 3.00 5.10 1.80 virginica

Simple Plots

plot of chunk unnamed-chunk-6

Exercise

練習Formula

  • data: cars
##    speed dist
## 1      4    2
## 2      4   10
## 3      7    4
## 4      7   22
## 5      8   16
## 6      9   10
## 7     10   18
## 8     10   26
## 9     10   34
## 10    11   17
## 11    11   28
## 12    12   14
## 13    12   20
## 14    12   24
## 15    12   28
## 16    13   26
## 17    13   34
## 18    13   34
## 19    13   46
## 20    14   26
## 21    14   36
## 22    14   60
## 23    14   80
## 24    15   20
## 25    15   26
## 26    15   54
## 27    16   32
## 28    16   40
## 29    17   32
## 30    17   40
## 31    17   50
## 32    18   42
## 33    18   56
## 34    18   76
## 35    18   84
## 36    19   36
## 37    19   46
## 38    19   68
## 39    20   32
## 40    20   48
## 41    20   52
## 42    20   56
## 43    20   64
## 44    22   66
## 45    23   54
## 46    24   70
## 47    24   92
## 48    24   93
## 49    24  120
## 50    25   85

plot of chunk unnamed-chunk-8

Exercise

練習Formula

  1. plot(speed~dist,cars)
  2. plot(dist~speed,cars)
  3. plot(~dist+speed,cars)

plot(y~x,data)

  • plot(dist~speed,cars)
  • speed for x axis
  • dist for y axis
  • data: cars

Simple Plots

  1. 趨勢

    • Line Chart
    • Bar Plot
  2. 比較、組成

    • Bar Plot
    • Pie Chart
  3. 分佈

    • Scatter Plot
    • Histgram
    • Box Plot

Simple Plots-Line Chart

plot(sin(seq(0,2*pi,1/50)),type='l')

plot of chunk unnamed-chunk-9

Exercise

Exercise

實質薪資倒退十五年?

Exercise

  • Data: salary_cpi
year salary cpi
1 69 8843 55.61
2 70 10677 60.67
3 71 11472 61.83
4 72 12122 62.17
5 73 13409 62.64
6 74 13980 62.16
7 75 15118 63.41
8 76 16496 63.69
9 77 18399 65.12
10 78 21247 67.56
11 79 24317 70.21
12 80 26881 73.59
13 81 29449 75.87
14 82 31708 78.21
15 83 33661 81.25
16 84 35389 84.69
17 85 36699 87.40
18 86 38489 86.94
19 87 39673 90.34
20 88 40842 89.53
21 89 41861 91.55
22 90 41960 90.51
23 91 41530 90.00
24 92 42065 89.58
25 93 42680 90.95
26 94 43159 93.23
27 95 43488 93.45
28 96 44392 97.94
29 97 44367 99.83
30 98 42182 98.22
31 99 44359 99.71
32 100 45508 100.74
33 101 45589 102.34
34 102 45664 103.04

Exercise

平均月薪

plot(salary_cpi[,1:2],type='l')

Exercise

實質薪資

salary_cpi$real_wage=salary_cpi$salary/salary_cpi$cpi*100
plot(real_wage~year,salary_cpi,type='l')

Exercise

Simple Plots-Bar plot

x=sample(1:150,50) #從1~150中隨機挑選50個數字
plot(iris[x,5])
  • 觀察趨勢
  • 比較不同類別的差異
  • 適用於數量較小的資料

Simple Plots-Bar plot

y=table(iris[x,5])
barplot(y,horiz=TRUE,las=1)
## 
##     setosa versicolor  virginica 
##         13         20         17

只接受vector or matrix

barplot(y)

Simple Plots-Bar plot

Data: VADeaths

Rural Male Rural Female Urban Male Urban Female
50-54 11.70 8.70 15.40 8.40
55-59 18.10 11.70 24.30 13.60
60-64 26.90 20.30 37.00 19.30
65-69 41.00 30.90 54.60 35.10
70-74 66.00 54.30 71.10 50.00

Simple Plots-Bar plot

barplot(VADeaths, beside = TRUE,
     legend=rownames(VADeaths))

barplot(VADeaths, 
     legend=rownames(VADeaths))    

Simple Plots-Pie

  • 比較同類別個群體之間的差異
  • 常見於新聞媒體
  • 只接受正數
## 
##     setosa versicolor  virginica 
##         13         20         17
pie(y)

Exercise

油電業薪資近9萬,是教服業的4倍?

  • 畫出薪資最低與最高的三個行業
  • Data: salary_2013

library(xts)
a=order(salary_2013$每人每月薪資)
salary_news=matrix(salary_2013$每人每月薪資[c(head(a,3),tail(a,3))],ncol = 6)
colnames(salary_news)=salary_2013$行業[c(head(a,3),tail(a,3))]
par(family='STKaiti') #Only for Mac!!!
mp=barplot(salary_news,col='dodgerblue4') #x軸座標
text(mp,10000,salary_news,col='gold') #標註薪資

Exercise

最高薪資與最低薪資

mp=barplot(salary_news,xaxt='n',col='dodgerblue4')
text(mp,-10000,colnames(salary_news),xpd=TRUE,srt=20,cex=1.5)

但是...,有些事情新聞沒說...

  • 若把行業別劃分更細,可以發現更高的薪水...
  • 以'salary_detail'再畫一次

Simple Plots-Scatter Plot

plot(iris[,3:4])
plot(Petal.Width~Petal.Length,data=iris)

Simple Plots-Scatter Plot

plot(iris[,1:3])
plot(~Sepal.Length+Sepal.Width+Petal.Length,data=iris)

Simple Plots-Box plot

plot(factor,number) #Don't Run!
plot(iris[,5],iris[,1])

Simple Plots-Box plot

boxplot(iris[,1]~iris[,5])
boxplot(Sepal.Length~Species,data=iris)

boxplot(iris[,1:2])

Simple Plots-Histgram

hist(iris[, 1], breaks = 4)

Add Something to a Plot

Add Something to a Plot- 低階繪圖

  1. 加上點、線、面、座標軸、文字說明
  2. 需要先有圖,才能畫出,無法獨立執行
    • points
    • lines
    • abline
    • arrows
    • segaments
    • grid
    • rect
    • polygon
  • 文字說明

    • text
    • mtext
    • title
    • legend
  • 座標軸

    • axis

Add Points & Lines

Add Points

Exercise

凸顯實質薪資成長率的沉淪

Exercise

real_wage=matrix(salary_cpi$real_wage,ncol=34)
colnames(real_wage)=salary_cpi[,1]
mp=barplot(real_wage,ylim=c(-20000,60000),col='dodgerblue4',ylab='TWD',xlab='year')

Exercise

ratio=diff(salary_cpi$real_wage)/salary_cpi$real_wage[1:33] #實質薪資成長率
lines(mp[2:34],ratio*500000,typ='o',pch=20,lwd=3,col=2) 
#畫上實質薪資成長率,為配合原圖的scale,乘上500000

Exercise

axis(4,seq(-20000,60000,10000),labels=paste(seq(-4,12,2),'%',sep = ""),col=2)
# 加上右邊Y軸,須考慮比例

Exercise

legend("bottomleft",c('實質薪資','實質薪資成長率'),bty='n',
   text.col=c('dodgerblue4','red'),
   col=c('dodgerblue4','red'),pch=c(15,20))# 加上圖例說明

Exercise

mtext(side=3,'成長率',adj=1) # 在plot的周邊加上說明

Add text with locator

locator(n=1)

Mathematical Annotation

x=seq(-pi,pi,pi/1000);y=sin(x)/abs(x)
plot(x,y)
text(0,0,expression(over(cos(x)%.%
sin(x),abs(x))))

Mathematical Annotation

Mathematical Annotation

Example- Batman Equation


f1 <- function(x) {
    y1 <- 3 * sqrt(1 - (x/7)^2)
    y2 <- -3 * sqrt(1 - (x/7)^2)
    y <- c(y1, y2)
    d <- data.frame(x = x, y = y)
    d <- d[d$y > -3 * sqrt(33)/7, ]
    return(d)
}
x1 <- c(seq(3, 7, 0.001), seq(-7, -3, 0.001))
d1 <- f1(x1)
x2 <- seq(-4, 4, 0.001)
y2 <- abs(x2/2) - (3 * sqrt(33) - 7) * x2^2/112 - 3 + sqrt(1 - (abs(abs(x2) - 
    2) - 1)^2)
x3 <- c(seq(0.75, 1, 0.001), seq(-1, -0.75, 0.001))
y3 <- 9 - 8 * abs(x3)
x4 <- c(seq(-0.5, -0.75, -0.001), seq(0.75, 0.5, -0.001))
y4 <- 3 * abs(x4) + 0.75
x5 <- seq(-0.5, 0.5, 0.001)
y5 <- rep(2.25, length(x5))
x6 <- c(seq(-3, -1, 0.001), seq(1, 3, 0.001))
y6 <- 6 * sqrt(10)/7 + (1.5 - 0.5 * abs(x6)) * sqrt(abs(abs(x6) - 1)/(abs(x6) - 
    1)) - 6 * sqrt(10) * sqrt(4 - (abs(x6) - 1)^2)/14
dd = data.frame(x = c(x2, x3, x4, x5, x6), y = c(y2, y3, y4, y5, y6))
d1 = rbind(d1, dd)
plot(d1, asp = 1)  # asp: x軸與y軸的比例
text(0, 0, expression(((over(x, 7))^2 * sqrt(over(abs(abs(x) - 3), abs(x) - 
    3)) + (over(y, 3))^2 * sqrt(over(abs(y^3 - over(sqrt(33), 7)), y^3 - over(sqrt(33), 
    7))) - 1) %.% (abs(over(x, 2)) - over(3 * sqrt(33) - 7, 122) * x^2 - 3 + 
    sqrt(1 - (abs(abs(x) - 2) - 1)^2) - y) %.% (9 * sqrt(over(abs((abs(x) - 
    1) * (abs(x) - over(3, 4))), (1 - abs(x)) * (abs(x) - over(3, 4)))) - 8 * 
    abs(x) - y)))  ## 方程式的上半段
text(0, -0.8, expression((3 * abs(x) + over(3, 4) * sqrt(over(abs((abs(x) - 
    over(3, 4)) * (abs(x) - over(1, 2))), (over(3, 4) - abs(x)) * (abs(x) - 
    over(1, 2)))) - y) %.% (over(9, 4) * sqrt(over((x - over(1, 2)) * (x + over(1, 
    2)), (over(1, 2) - x) * (over(1, 2) + x))) - y) %.% (over(6 * sqrt(10), 
    7) + over(3 - abs(x), 2) * sqrt(over(abs(abs(x) - 1), abs(x) - 1)) - over(6 * 
    sqrt(10), 14) * sqrt(4 - (abs(x) - 1)^2) - y) == 0))  ##方程式的下半段

Adjust

Adjust

  • Permanent Changes

par(...)
  • Temporary Changes (with Simple Plots)
  • Graphical Elements
  • Figure Margins
  • Multiple Figure Environment

Graphical Elements

Graphical Elements

Colors

colors() #內建的顏色
rainbow(144) #產生彩虹色
palette(rainbow(144)) #將彩虹色設定成預設顏色
colorRampPalette(c('red','green'))(10) #紅綠漸層 

plot of chunk unnamed-chunk-40

Example- Barnsley Fern Fractal

plot of chunk unnamed-chunk-41

Example- Barnsley Fern Fractal

想要讓葉子顏色漸層

data("df_brower", package = "DSC2014Tutorial")
a = order(df[, 2])
plot(x = df[a, 2], y = df[a, 1], cex = 0.1, asp = 1,
col=colorRampPalette(c("darkgreen", "lightgreen"))(10000))

Example- 偽ggplot

Example- 偽ggplot

plot(iris[, 3:4], bty = "n", axes = FALSE)
## 利用rect將背景顏色換掉 par('usr'):繪圖範圍的座標
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], border = "grey89", 
    col = "grey89")
grid(col = "white", lty = 1)  ## 加上grid
axis(1, col = "lightgrey")  ## 加上X軸
axis(2, col = "lightgrey")  ## 加上Y軸
points(iris[, 3:4], pch = 20)  ## 最後畫上data

Figure Margins

par(mar = c(3, 1, 1, 1))#the number of lines of margin
par(mai = c(3, 1, 1, 1))#margin size specified in inches

Multiple Figure Environment

par(mfrow=c(3,2))

Multiple Figure Environment

nf=layout(matrix(c(2,1,0,3), 2, 2), widths=c(3,1), heights=c(1,3))
layout.show(nf)

Multiple Figure Environment

layout(matrix(c(2, 1, 0, 3), 2, 2), widths = c(3, 1), heights = c(1, 3))
xhist = hist(iris[, 3], plot = FALSE)  # get distribution
yhist = hist(iris[, 4], plot = FALSE)  # get distribution
par(mar = c(5, 5, 1, 1))  #調整邊界
plot(iris[, 3:4])
par(mar = c(0, 3, 1, 1))  #調整邊界
barplot(xhist$counts, axes = FALSE, space = 0)
par(mar = c(3, 1, 1, 0))  #調整邊界
barplot(yhist$counts, axes = FALSE, space = 0, horiz = TRUE)

Multiple Figure Environment

調整邊界前

調整邊界後

Exercise

極端的工時與薪資

  • 找到工時和薪資太誇張的工作
  • 將工時和薪資在同一畫面上呈現
  • Data: salary_detail

time_salary=cbind(hours=salary_detail$平均.工時,TWD=salary_detail$每人每月薪資)
rownames(time_salary)=salary_detail$行業

Exercise

Exercise

plot(TWD~hours,time_salary)

Exercise

ind=identify(time_salary,plot=FALSE)
  • identify可以偵測圖上選擇的點之index
  • 執行上述指令後,在圖上以滑鼠點擊選擇欲觀察的點
  • 選完後,在Console按ESC鍵

Exercise

points(time_salary[ind,],pch=20,col='red')
text(time_salary[ind,],rownames(time_salary)[ind],col='dodgerblue',font=2)

Exercise

利用layout,將Scatter plot與Bar plot結合

layout(matrix(c(1,1,2,3), 2, 2), widths=c(3,6), heights=c(2,2))
plot(TWD~hours,time_salary,xlim=c(100,260),ylim=c(2e4,1.2e5))
points(time_salary[ind,],pch=20,col='red')
text(time_salary[ind,],rownames(time_salary)[ind],pos=1:4,col='dodgerblue',font=2)
mp1=barplot(time_salary[ind,1],ylab='hours')
text(mp1,50,time_salary[ind,1])
barplot(time_salary[ind,2],ylab='TWD')
text(mp1,10000,time_salary[ind,2])

Others

Save image

png(file='test.png')
plot(iris[,3:4])
dev.off()
  • png
  • pdf
  • jpeg
  • bmp
  • tiff

wordcloud

install.packages("wordcloud")
library("wordcloud")
wordcloud(words=c(letters,LETTERS,0:9),freq=seq(1,1000,len=62))

Project

Browser market

Project

Answer

plot_color=c("gray22", "deepskyblue4", "firebrick2", "springgreen4", "orange",'gray50')
palette(plot_color) 
layout(matrix(c(3,1,2,1), 2, 2), widths=c(2,2), heights=c(2,2))
par(mar=c(4,4,0,2),cex=1.2)
plot(browser_table[,1:2],lwd=2,ylim=c(0,60),pch=20,type='o')
for (i in 3:7){
  lines(browser_table[,c(1,i)],type='o',col=i-1,lwd=2,pch=20)
}
par(mar=c(0,0,0,0.1),cex=1.2)
pie(as.numeric(tail(browser_table,1)[2:7]),col=1:6,labels="")
legend('topleft',legend=colnames(browser_table)[2:7],
  text.col=1:6,col=1:6,pch=20,bty='n')
par(mar=c(0,0,0,0),cex=1)
wordcloud(colnames(browser_table)[2:7],tail(browser_table,1)[,2:7]*10000,scale=c(6,1),
 ordered.colors = TRUE,colors =1:6) #字不見時,可調整scale

Thank you!