Reputation: 159
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?
Upvotes: 4
Views: 3089
Reputation: 162321
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)
Upvotes: 2
Reputation: 60934
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.
Upvotes: 2