登录
首页精彩阅读R语言散点图
R语言散点图
2017-06-20
收藏

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

当我们上面的代码执行时,它产生以下结果:

散点图矩阵

当我们有两个以上的变量,我们希望用散点图矩阵找到对其余的变量之间的相关性。我们使用 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()

当执行上面的代码中,我们得到以下输出:

数据分析咨询请扫描二维码

客服在线
立即咨询