[R] barplot at specific x values

Deepayan Sarkar deepayan.sarkar at gmail.com
Thu Nov 12 21:37:17 CET 2009


On Thu, Nov 12, 2009 at 8:54 AM, Richard M. Heiberger <rmh at temple.edu> wrote:
> Bastian Pöschl wrote:
>>
>> Dear useRs,
>>
>> I search for a possibillity to plot stacked bars at specific x positions.
>> I tried and tried, but the only way i got something adequate was by using
>> lowlevel plots segments(). That is quiet ok, but will not please eyes
>> without a lot of par() lines.
>>
>>
>> dh<-data.frame(longitude=abs(rnorm(5)),deers=abs(rnorm(5)),humans=abs(rnorm(5)))
>>
>> plot(dh$longitude,apply(dh[,2:3], 1,
>> sum),type="n",ylim=c(0,max(apply(dh[,2:3], 1, sum))))
>> segments(dh$longitude,0,dh$longitude,dh$deers, col="green", lwd=12)
>> segments(dh$longitude,dh$deers,dh$longitude,dh$deers+dh$humans, col="red",
>> lwd=12)
>>
>> I hope somebody is experienced in doing such plots or somebody just knows
>> how to do it.
>>
>> Bastian
>>
>>
>
> tmp.lattice <- barchart(deers+humans ~ longitude, data=dh, stack=TRUE,
> horizontal=FALSE, auto.key=TRUE, box.ratio=.03)
> tmp.lattice$panel.args[[1]]$x <-
> rep(dh$longitude,2)[tmp.lattice$panel.args[[1]]$subscripts]
> tmp.lattice$x.limits <- range(pretty(dh$longitude))
> tmp.lattice
>
> This works.  I don't like this solution because I had to modify the trellis
> object after the fact instead of
> specifying it with commands.  The panel.barchart says
> |     y|        Horizontal location of bars, possibly factor
>
> which implies that numeric values would be acceptable, but the barchart
> function coerces the values to effectively
>  as.numeric(factor(longitude))

Yes, so the trick would be to use panel.barchart but not barchart.
Using xyplot instead gets you most of the way, but you need a few more
tweaks to get everything right (mainly, the limit calculations):

xyplot(deers+humans ~ longitude, data=dh, panel = panel.barchart,
       stack=TRUE, horizontal=FALSE,
       auto.key=list(rectangles = TRUE, points = FALSE),
       box.width=0.1,
       ylim = extendrange(c(0, with(dh, max(deers + humans)))))

-Deepayan

> so they appear in the panel function as 1 1 2 2 3 3 4 4 5 5
>
> I tried a few ways to make the longitude stay numeric and didn't hit on any
> that worked.
>
> Deepayan, can you help here?
>
> Rich
>
>
>




More information about the R-help mailing list