[R] combine barchart and xyplot in lattice

Deepayan Sarkar deep@y@n@@@rk@r @end|ng |rom gm@||@com
Sat Nov 18 16:08:47 CET 2023


On Sat, 18 Nov 2023 at 06:44, Naresh Gurbuxani
<naresh_gurbuxani using hotmail.com> wrote:
>
> In below graph, I would like to add two vertical lines using
> panel.abline().  Is this possible?

I assume you want the 'v' variable in panel.abline() to be interpreted
in the context of your x-axis, which here represents a factor
variable. Unless two factor variables have the same levels, their
values don't really mean the same thing. So either you need to specify
the levels, or make the axis numeric:

# option 1 - factor
xyplot(count ~ as.factor(hour), type = "l", lwd = 2,
       col = 2, data = vehicles,
       panel = function(x, y, ...) {
           panel.xyplot(x, y, ...)
           panel.abline(v = factor(c("9", "17"), levels = levels(x)),
                        lty = 2, col = "gray")
       })

# option 2 - numeric
xyplot(count ~ hour, type = "l", lwd = 2,
       col = 2, data = vehicles,
       panel = function(x, y, ...) {
           panel.xyplot(x, y, ...)
           panel.abline(v = c(9, 17), lty = 2, col = "gray")
       })

Best,
-Deepayan

>
> Thanks,
> Naresh
>
> mydf <- data.frame(hour = rep(6:20, 2),
> traffic = c(round(dnorm(6:20, 9, 3) * 10000), round(dnorm(6:20, 17, 4) *
> 10000)),
> direction = rep(c("inbound", "outbound"), c(15, 15)))
>
> vehicles <- data.frame(hour = 6:20,
> count = c(100, 120, 140, 125, 105, 80, 70, 75, 80, 100, 110, 120, 115,
> 110, 100))
>
> library(lattice)
> library(latticeExtra)
>
> # This works
> mybars <- barchart(traffic ~ as.factor(hour), groups = direction,
> stack = TRUE, horizontal = FALSE, data = mydf,
> auto.key = list(columns = 2, space = "bottom"), xlab = "hour")
>
> mylines <- xyplot(count ~ as.factor(hour), type = "l", lwd = 2,
> col = 2, data = vehicles)
>
> mybars + mylines
>
> # This does not work.  Lines are not correctly placed.
> mylines <- xyplot(count ~ as.factor(hour), type = "l", lwd = 2,
> col = 2, data = vehicles, panel = function(x, y, ...) {
> panel.xyplot(x, y, ...)
> panel.abliine(v = as.factor(c(9, 17)), lty = 2, col = "gray")
> })
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list