analyticsPierce
analyticsPierce

Reputation: 3025

How to format number values for ggplot2 legend?

I am working on finishing up a graph generated using ggplot2 like so...

ggplot(timeSeries, aes(x=Date, y=Unique.Visitors, colour=Revenue)) 
+ geom_point() + stat_smooth() + scale_y_continuous(formatter=comma)

I have attached the result and you can see the numeric values in the legend for Revenue do not have a comma. How can I add a comma to those values? I was able to use scale_y_continuous for the axis, can that be used for the legend also?

alt text

Upvotes: 31

Views: 29436

Answers (4)

filups21
filups21

Reputation: 1907

Note that comma and comma_format() have been superceded by label_comma(). Here's what I typically use:

... + 
scale_y_continuous(labels = scales::label_comma()) +
scale_colour_continuous(labels = scales::label_comma()) 

Upvotes: 1

TomS
TomS

Reputation: 226

...as I stumbled over this older thread, maybe it makes sense to add you need to load library("scales"), otherwise you get the following error message

Error in check_breaks_labels(breaks, labels) : object 'comma' not found

Upvotes: 8

Matt Parker
Matt Parker

Reputation: 27339

Note 2014-07-16: the syntax in this answer has been obsolete for some time. Use metasequoia's answer!


Yep - just a matter of getting the right scale_colour_ layer figured out. Try:

ggplot(timeSeries, aes(x = Date, y = Unique.Visitors, colour = Revenue)) +
    geom_point() +
    stat_smooth() +
    scale_y_continuous(formatter = comma) +
    scale_colour_continuous(formatter = comma)

I personally would also move my the colour mapping to the geom_point layer, so that it doesn't give you that odd line behind the dot in the legend:

ggplot(timeSeries, aes(x = Date, y = Unique.Visitors)) +
    geom_point(aes(colour = Revenue)) +
    stat_smooth() +
    scale_y_continuous(formatter = comma) +
    scale_colour_continuous(formatter = comma)

Upvotes: 14

metasequoia
metasequoia

Reputation: 7264

Just to keep current, in ggplot2_0.9.3 the working syntax is:

require(scales)
ggplot(timeSeries, aes(x=Date, y=Unique.Visitors, colour=Revenue)) +
    geom_point() +
    stat_smooth() +
    scale_y_continuous(labels=comma) +
    scale_colour_continuous(labels=comma)

Also see this exchange

Upvotes: 62

Related Questions