[R] Lattice, combine histogram and line graph

Joshua Wiley jwiley.psych at gmail.com
Mon Jan 10 03:16:32 CET 2011


Hi Jim,

Some example data would help us.  I typically think of a histogram as
the frequency of values falling within a certain range (determined by
bins).  Since they are univariate plots, I'm not sure how you are
planning on adding a line graph to that.  If you just want bars of the
average gasoline price at different years, perhaps something along
these lines would work for you:

## Load required packages
require(lattice)
require(latticeExtra)

## Sample Data
dat <- data.frame(year = 1996:2010,
  x1 = rnorm(15, 3, .2), x2 = rnorm(15, 200, 1))

## Base xyplot (not a histogram) adding a layer with different y axis
xyplot(x1 ~ year, data = dat, type = "h") +
  as.layer(xyplot(x2 ~ year, data = dat, type = "l", col = "black"),
  y.same = FALSE)

## See
?xyplot
?as.layer
?hist # for info about histograms

HTH,

Josh

On Sun, Jan 9, 2011 at 5:13 PM, Jim Burke <j.burke at earthlink.net> wrote:
> Hello everyone,
>
> I have a simple histogram of gasoline prices going back a few years that I
> want to insert a line graph of consumer price index (cpi) over the
> histogram.  I have looked through the "Lattice" book by Deepayan Sarkar but
> don't see anything there. How might this be done? An example would be
> wonderful.
>
> Current code snippet follows. For example additional field to add as a line
> graph would be a cpi calculation like "gas_data$regular * (2010_cpi /
> gas_data$year )".
>
> xyplot( regular ~ as.Date(gas_data$dates,"%b %d, %Y") , data = gas_data,
>       type = c("g", "h" ))
>
> Thanks,
> Jim Burke
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list