位置:首頁 > 大數據教學 > R語言教學 > R語言散點圖

R語言散點圖

散點圖顯示繪製坐標平麵多點。每個點代表兩個變量的值。一個變量被選擇在水平軸和另一個在垂直軸。

使用 plot()函數來創建簡單的散點圖。

語法

R中創造散點圖的基本語法是:


plot(x, y, main, xlab, ylab, xlim, ylim, axes)

以下是所使用的參數的說明:

  • x 是數據集,其值在水平坐標
  • y 是數據集,其值在垂直坐標
  • main 是圖形的標題
  • xlab 是水平軸上的標簽
  • ylab 是垂直軸上的標簽
  • xlim 是用於限製繪製x的值
  • ylim 是用於限製繪製y的值
  • axes 指示是否兩個軸應在圖上繪製

示例

我們使用的數據集“mtcars”可在R環境中創建一個基本散點圖。讓我們使用 mtcars 中的 "wt" 和 "mpg" 的列。

input <- mtcars[,c('wt','mpg')]
print(head(input))

當我們上麵的代碼執行時,它產生以下結果:

                wt  mpg
Mazda RX4         2.620 21.0
Mazda RX4 Wag     2.875 21.0
Datsun 710        2.320 22.8
Hornet 4 Drive    3.215 21.4
Hornet Sportabout 3.440 18.7
Valiant           3.460 18.1

創建散點圖

下麵的腳本將創建wt(重量比)和 mpg(英裡每加侖)之間的關係的散點圖圖表。

# Get the input values.
input <- mtcars[,c('wt','mpg')]

# Give the chart file a name.
png(file = "scatterplot.png")

# Plot the chart for cars with weight between 2.5 to 5 and mileage between 15 and 30.
plot(x=input$wt,y=input$mpg,
     xlab="Weight",
     ylab="Milage",
     xlim=c(2.5,5),
     ylim=c(15,30),		 
     main="Weight vs Milage"
     )
	 
# Save the file.
dev.off()

當我們上麵的代碼執行時,它產生以下結果:

Scatter Plot using R

散點圖矩陣

當我們有兩個以上的變量,我們希望用散點圖矩陣找到對其餘的變量之間的相關性。我們使用 pairs() 函數創建散點圖矩陣。

語法

R中創建散點圖矩陣的基本語法是:

pairs(formula, data)

以下是所使用的參數的說明:

  • formula 表示一係列的配對使用的變量。
  • data 表示所述數據集從該變量將被采用。

示例

每個變量配對與每個其餘的變量。散點圖繪製配對。

# Give the chart file a name.
png(file = "scatterplot_matrices.png")

# Plot the matrices between 4 variables giving 12 plots.

# One variable with 3 others and total 4 variables.

pairs(~wt+mpg+disp+cyl,data=mtcars,
   main="Scatterplot Matrix")

# Save the file.
dev.off()

當執行上麵的代碼中,我們得到以下輸出:

Scatter Plot Matrices using R