我正在进行多元线性回归的第一道课程,所以我还是R的初学者。我们最近学到了一些关于在水平和垂直方向上拍摄双变量散点图数据的方法。我想知道的是如何超越基本的散点图,并利用有条件地按片分组数据来检查模式。
例如,我正在处理银行的高辛烷值数据,我们将员工当前的薪水csalary
归结为他们的初始薪水bsalary
。这是我的数据框架的样子。
> str(data)
'data.frame': 474 obs. of 10 variables:
$ id : num 628 630 632 633 635 637 641 649 650 652 ...
$ bsalary: num 8400 24000 10200 8700 17400 ...
$ gender : Factor w/ 2 levels "Male","Female": 1 1 1 1 1 1 1 1 1 1 ...
$ time : num 81 73 83 93 83 80 79 67 96 77 ...
$ age : num 28.5 40.3 31.1 31.2 41.9 ...
$ csalary: num 16080 41400 21960 19200 28350 ...
$ educlvl: num 16 16 15 16 19 18 15 15 15 12 ...
$ work : num 0.25 12.5 4.08 1.83 13 ...
$ jobcat : Factor w/ 7 levels "Clerical","Office Trainee",..: 4 5 5 4 5 4 1 1 1 3 ...
$ ethnic : Factor w/ 2 levels "White","Non-White": 1 1 1 1 1 1 1 1 1 1 ...
为了探索bsalary
和csalary
之间的关系,我使用lattice
库的一些功能创建了一个散点图。我沿着bsalary
任意画了5000美元的垂直线。
library (lattice)
# Constructing vertical "slices" of our csalary ~ bsalary data
# First we define a vector with our slice points, in this case
# $5,000 bsalary increments
bslices = seq (from = 5000, to = 30000, by = 5000)
length (bslices)
xyplot (csalary ~ bsalary,
main = "Current Bank Employee Salary as Predicted by Beginning Salary",
xlab = "Beginning Salary ($USD)",
ylab = "Current Salary ($USD)",
panel = function(...){
panel.abline(v = bslices, col="red", lwd=2);
panel.xyplot(...);
}
)
上面的代码让我知道了。
Rplot002.pdf (1 page) http://img.skitch.com/20100222-tkcu613r9cjqc4cs3314hc1i7h.preview.jpg哪个太棒了。但我觉得应该有一种简单的方法可以从我的数据中生成将切片数据分组到箱图中的图形:
01LinReg.pdf (page 3 of 25) http://img.skitch.com/20100222-rhjudjw4txnfu43pycuqneuqan.preview.jpg
或堆叠点散点图,再次按切片分组,如下所示:
01LinReg.pdf (page 3 of 25) http://img.skitch.com/20100222-cgsqwnhnd26k5qhb6gb2sjk1bs.preview.jpg
最后,我的问题是如何将原始散点图数据转换为有条件分组的数据。我觉得格子有一些简单的底层特征(甚至更简单的绘图命令,不需要它),这将允许我开始切片我的数据来探索模式。
在此先感谢您的帮助!
答案 0 :(得分:2)
您可以使用cut()函数将数据切分为序数类别。然后ggplot2的qplot函数可以很容易地创建你想要的图。
library(ggplot2)
#fake data
csalary <- rnorm(100,,100)
bsalary <- csalary +rnorm(100,,10)
#Regular Scatter Plot
qplot(bsalary,csalary)
#Stacked dot plot
qplot(cut(bsalary,10),csalary)
#box-plot
qplot(cut(bsalary,10),csalary,geom="boxplot")
答案 1 :(得分:2)
你真的想这样做吗?将连续变量转换为序数变量会抛弃信息,因为X变量的不同值最终会出现在同一个bin中。我认为你的boxplot图形传达的信息比散点图少得多。
如果由于点重叠而对散点图不满意,保留信息的一种方法是添加捕获趋势的平滑曲线。查看lowess
的文档以获取示例。
在你的图表中,工资高于20,000美元的三个观察结果将剩余的观察结果推向了一个角落。删除它们并重新绘制会产生更好的图形。
像你这样的偏斜数据的另一种方法是绘制变量的对数而不是变量本身。
答案 2 :(得分:2)
不是通过条件变量的值对数据进行切片(将连续变量转换为离散变量),而是使用内核函数进行条件化更有效。有这样做的包:hdrcde。查看帮助文件中的示例。
答案 3 :(得分:0)
此页面为您解释 http://www.statmethods.net/advgraphs/trellis.html
您基本上想要更改图表的等式。 他们应该更像
csalary~bsalary | gender
应根据不同的性别价值将图表分开。连续条件变量有一堆控制语言。