[R] Changing X axis of ggplot

Joshua Wiley jwiley.psych at gmail.com
Wed Jan 4 06:30:26 CET 2012


Hi Aren,

Thanks for sending the data.  I poked around a bit, and here was what
I came up with (a bit of a hack really, but perhaps acceptable
enough).  lbl_formatter looks like another way to go.

require(ggplot2)
require(chron)

## hack to deal with non exported method
parse.format <- chron:::parse.format

## now just use chron's format.times() function as your formatter:
ggplot(dallas, aes(x = offense_time)) +
  geom_bar() +
  coord_polar() +
  scale_x_continuous(formatter = chron:::format.times)

Somewhat sensibly, the ~22-06 hours are relatively light (at least in
the little subset of your data I looked at).

Note that the ::: is used because I am using functions in chron it
never meant for end users to use directly.

Happy graphing!

Josh


On Tue, Jan 3, 2012 at 6:57 PM, Aren Cambre <aren at arencambre.com> wrote:
> Got it figured out. I found this post on the ggplot2 Google Group:
> http://groups.google.com/group/ggplot2/browse_thread/thread/698e658b6dfec56c/5390824dab4a1cd7
>
> It recommends you make this function:
> lbl_formatter <- function(x) {
>    h <- floor(x/60)
>    m <- floor(x %% 60)
>    s <- round(60*(x %% 1))  # Round to nearest second
>    sprintf('%02d:%02d:%02d', h, m, s)
> }
>
> Then you assign it as the formatter using scale_x_continuous(formatter
> = lbl_formatter).
>
> Aren
>
> On Mon, Jan 2, 2012 at 9:34 PM, Aren Cambre <aren at arencambre.com> wrote:
>>
>> Thanks to Joshua Wiley for turning me on to ggplot2.
>>
>> I am making a plot using this:
>> p <- ggplot(dallas, aes(x = offense_hour)) + geom_bar() + coord_polar()
>>
>> Dallas is a data frame, and offense_hour is a column with chron
>> objects from the chron library. In this case, the chron object was
>> created with the times function. It is only a time (H:M:S) with no
>> date attached.
>>
>> The plot shows up fine, but the X axis labels are 0.0 through 1.0. How
>> do I convert this to 0:00 through 23:59 (or whatever may be
>> appropriate given the breaks)?
>>
>> My searches lead me to scale_x_discrete, but I am not clear if that's
>> even the right function.
>>
>> Aren
>
> ______________________________________________
> 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
Programmer Analyst II, Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list