R語言 散點圖

2022-06-16 15:42 更新

散點圖顯示在笛卡爾平面中繪制的許多點。 每個點表示兩個變量的值。 在水平軸上選擇一個變量,在垂直軸上選擇另一個變量。
使用plot()函數(shù)創(chuàng)建簡單散點圖。

語法

在R語言中創(chuàng)建散點圖的基本語法是 -

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

以下是所使用的參數(shù)的描述 - 

  • x是其值為水平坐標(biāo)的數(shù)據(jù)集。

  • y是其值是垂直坐標(biāo)的數(shù)據(jù)集。

  • main要是圖形的圖塊。

  • xlab是水平軸上的標(biāo)簽。

  • ylab是垂直軸上的標(biāo)簽。

  • xlim是用于繪圖的x的值的極限。

  • ylim是用于繪圖的y的值的極限。

  • axes指示是否應(yīng)在繪圖上繪制兩個軸。

我們使用R語言環(huán)境中可用的數(shù)據(jù)集“mtcars”來創(chuàng)建基本散點圖。 讓我們使用mtcars中的“wt”和“mpg”列。

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

當(dāng)我們執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果 -

                    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

創(chuàng)建散點圖

以下腳本將為wt(重量)和mpg(英里/加侖)之間的關(guān)系創(chuàng)建一個散點圖。

# 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()

當(dāng)我們執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果 -

,使用R散點圖

散點圖矩陣

當(dāng)我們有兩個以上的變量,我們想找到一個變量和其余變量之間的相關(guān)性,我們使用散點圖矩陣。 我們使用pairs()函數(shù)創(chuàng)建散點圖的矩陣。

語法

在R中創(chuàng)建散點圖矩陣的基本語法是 -

pairs(formula, data)

以下是所使用的參數(shù)的描述 - 

  • formula表示成對使用的一系列變量。

  • data表示將從其獲取變量的數(shù)據(jù)集。

每個變量與每個剩余變量配對。 為每對繪制散點圖。

# 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()

當(dāng)執(zhí)行上面的代碼中,我們得到以下輸出。

散點圖矩陣,使用R
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號