[R] ggplot: Trouble with xlim() and discrete scales

David Winsemius dwinsemius at comcast.net
Tue May 11 01:48:01 CEST 2010


On May 10, 2010, at 7:36 PM, John Rauser wrote:

> I'm learning ggplot and am a little confused. Sometimes discrete  
> scales work
> like I'd expect, and sometimes they don't.  For example...
>
> This works exactly like one would expect:
>
> df<-data.frame(names=c("Bob","Mary","Joe","Bob","Bob"))
> ggplot(df,aes(names))+geom_histogram()
>
> But this yields an error:
>
> ggplot(df,aes(names))+geom_histogram()+xlim("Bob")
> Error in data.frame(count = as.numeric(tapply(weight, bins, sum,  
> na.rm =
> TRUE))$
>  arguments imply differing number of rows: 0, 1

Well, a range with only one value seems a bit  ... degenerate?
>
> ...as does this:
>
> ggplot(df,aes(names))+geom_histogram()+xlim("Bob","Mary")
>

 > str(df)
'data.frame':	5 obs. of  1 variable:
  $ names: Factor w/ 3 levels "Bob","Joe","Mary": 1 3 2 1 1

> ... but this works fine:
>
> ggplot(df,aes(names))+geom_histogram()+xlim("Bob","Mary","Joe")

So now that "range" covers the factor's possible values, and it  
appears Hadley's coding is willing to a accept a degree of abstraction.

>
> ... and curiously, so does this:
>
> ggplot(df,aes(names))+geom_histogram() 
> +xlim("Bob","Mary","Joe","Frank")
>
> ... and even more confusingly, this works perfectly:
>
> ggplot(df,aes(names,..density..,group=1))+geom_histogram() 
> +xlim("Bob","Mary")
>
>
> This feels like a bug, but perhaps I'm doing something dumb.

Looks dumb to me.

> Can anyone
> clarify?
>
>
> And while I have your attention: as a ggplot novice, I often find  
> myself
> getting cryptic error messages like the one above.  Nearly always  
> this is
> because I'm asking it to do something unreasonable, but it often  
> takes me
> quite a long time to figure out my error.  Does anyone have general  
> tips for
> debugging ggplot commands?  Anything better than summary(p)?

Use str to look at your data. gives you further information about  
classes.


David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list