Multiple ablines in xyplot

删除回忆录丶 提交于 2019-12-12 12:13:25

问题


I have a "long" dataframe defined as:

q <- data.frame(Indicator.Code=factor(),Year=numeric(),Value=numeric())

and am trying to plot in a single xyplot the values as a function of the year, for each different Indicator.Code, as follows

xyplot( Value~Year,data=q,group=Indicator.Code)

So far, so good. Now I am trying to add lines corresponding to the linear regressions

rlm(q$Value[q$Indicator.Code==a]~q$Year[q$Indicator.Code==a])

for all the values of Indicator.Code.

I do not know how to do it. The usual way to add regression lines, i.e

xyplot( Value~Year,data=q,group=Indicator.Code),
panel = function(x, y) {
  panel.xyplot(x, y)
  panel.abline(rlm(y ~ x))
}))

does not work properly (it computes a single regression, and adds a single regression line, for the whole dataset). Besides, I have already computed the regressions (I need them for things other than graphics too), and hate the idea of having to recompute them.

Any hints a novice could follow?


回答1:


I'm a ggplot2 addict: ). The equivalent in ggplot2 does what you expect:

library(ggplot2)
ggplot(q, aes(x = Year, y = Value, color = Indicator.Code)) + 
   geom_point() + stat_smooth(method = "rlm")

Note that I believe you pass any function as method, but without a reproducible example it is hard to check.




回答2:


For a customized panel function that plots separate symbols for each group, lattice requires that you wrap the actual panel function in a call to panel.superpose(). Here's an example, using data in the mtcars data.frame.

library(lattice)
library(MASS)

myPanel <- function(x,y,...) {
    panel.xyplot(x,y,...)
    panel.abline(rlm(y~x), ...)
}

xyplot(mpg~disp, group = cyl, data = mtcars,
       panel = function(...) panel.superpose(panel.groups = myPanel, ...))

## Or, equivalently:
xyplot(mpg~disp, group = cyl, data = mtcars, 
       panel = panel.superpose, panel.groups = myPanel)



来源:https://stackoverflow.com/questions/16361766/multiple-ablines-in-xyplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!