R 圖表入門

  • 散點圖

你有兩個向量,你想繪製它們。

x_values <- rnorm(n = 20 , mean = 5 , sd = 8) #20 values generated from Normal(5,8)
y_values <- rbeta(n = 20 , shape1 = 500 , shape2 = 10) #20 values generated from Beta(500,10)

如果要建立垂直軸為 y_values 且水平軸為 x_values 的繪圖,可以使用以下命令:

plot(x = x_values, y = y_values, type = "p") #standard scatter-plot
plot(x = x_values, y = y_values, type = "l") # plot with lines
plot(x = x_values, y = y_values, type = "n") # empty plot

你可以在控制檯中鍵入 ?plot() 以閱讀更多選項。

  • 箱形圖

你有一些變數,你想檢查他們的分佈

#boxplot is an easy way to see if we have some outliers in the data.
   
z<- rbeta(20 , 500 , 10) #generating values from beta distribution
z[c(19 , 20)] <- c(0.97 , 1.05) # replace the two last values with outliers      
boxplot(z) # the two points are the outliers of variable z.
  • 直方圖

繪製直方圖的簡便方法

hist(x = x_values) # Histogram for x vector
hist(x = x_values, breaks = 3) #use breaks to set the numbers of bars you want
  • 餅狀圖

如果你想要顯示變數的頻率,只需繪製餅圖

首先,我們必須生成具有頻率的資料,例如:

P <- c(rep('A' , 3) , rep('B' , 10) , rep('C' , 7) )
t <- table(P) # this is a frequency matrix of variable P
pie(t) # And this is a visual version of the matrix above