R晶格正确标记点与xyplot

时间:2016-04-12 10:05:10

标签: r plot panel lattice

library(lattice)

# load reproducible data set
attach(mtcars)

# change the rownames into a column value and remove the rownames
mtcars <- as.data.frame(cbind(car.name=rownames(mtcars), mtcars))
rownames(mtcars) <- NULL

# panel function parameters so that I label the points that are 100 units
# different between the hp and disp values and label the points with the car name

panel = function (x, y, ...) {
    panel.xyplot(x, y, ...)
    x1 <- x[x-y > 100 | y-x > 100]
    y1 <- y[x-y > 100 | y-x > 100]
    panel.text(x1, y1, labels=mtcars$car.name, pos=3)   
}

#calling the xyplot
xyplot(hp~disp, data=mtcars, main=NULL, ylab="hp", xlab="disp", 
       jitter=TRUE, pch=1, as.table=TRUE, panel=panel)

xyplot of mtcars

我可以看到,hpdisp之间显示100个单位差异的所有点都有一个标签。 但是,标签与表中的实际数据不匹配。 我可以通过首先按列mtcars按降序排序disp来说明这一点:

mtcars <- mtcars[order(-mtcars$disp),]
head(mtcars)
              car.name  mpg cyl disp  hp drat    wt  qsec vs am gear carb
15  Cadillac Fleetwood 10.4   8  472 205 2.93 5.250 17.98  0  0    3    4
16 Lincoln Continental 10.4   8  460 215 3.00 5.424 17.82  0  0    3    4
17   Chrysler Imperial 14.7   8  440 230 3.23 5.345 17.42  0  0    3    4
25    Pontiac Firebird 19.2   8  400 175 3.08 3.845 17.05  0  0    3    2
5    Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
7           Duster 360 14.3   8  360 245 3.21 3.570 15.84  0  0    3    4

正如您所看到的,car.name disp disp是最高hp的凯迪拉克弗利特伍德,而且未在图表中标注,实际上会出现另一个车名。

如何根据我的条件显示正确的车名,以便只标记$account = new Account(); $account->retrieve($_REQUEST['record']); $contacts = $account->get_linked_beans('contacts','Contact'); foreach ( $contacts as $contact ) { echo "{$contact->name}\n" } In [7]: df1['a'] = df2['a'] In [8]: df1['c'] = df2['c'] In [14]: df1[['a','c']] = df2[['a','c']] 之间有> 100单位差异的车?我的面板功能出了问题。

1 个答案:

答案 0 :(得分:2)

x1y1mtcars$carname的长度不同,因此标签不对应:

length(x1)=11
length(y1)=11,
length(mtcars$carname)=32

以下是修改后的版本:

panel = function (x, y, ...) {
    panel.xyplot(x, y, ...)
    v <- abs(x - y) > 100
    panel.text(x[v], y[v], labels=mtcars$car.name[v], pos=3)
}

xyplot(hp~disp, data=mtcars, main=NULL, ylab="hp", xlab="disp", 
       jitter=TRUE, pch=1, as.table=TRUE, panel=panel)

enter image description here

相关问题