[R] Lattice, combine histogram and line graph

Jim Burke j.burke at earthlink.net
Mon Jan 10 05:51:47 CET 2011


Thanks Josh, Gabor, and David,

I appreciate your suggestions and the time you took to think about this. 
This was all most helpful. Gabor I will look at the zoo package soon. 
Sounds interesting.

Below is what worked for me from Josh to overlay a line graph on a 
histogram.


obj1 <- xyplot( regular ~ as.Date(gas_data$dates,"%b %d, %Y") , data = 
gas_data,
type = c("g", "h" ) )

obj2 <- xyplot( (gas_data$regular * (cpi_2010 / gas_data$cpi) ) ~ 
as.Date(gas_data$dates,"%b %d, %Y") , data = gas_data,
type = c( "l" ), col = "black" )

obj1 + as.layer(obj2, style = 2, axes = NULL, )


Have a great week,
Jim


Joshua Wiley wrote:
> 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.
>>
>>     
>
>
>
>



More information about the R-help mailing list