Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format number values for ggplot2 legend?

Tags:

r

ggplot2

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

like image 785
analyticsPierce Avatar asked Oct 22 '10 01:10

analyticsPierce


People also ask

How do I change the legend value in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do I change the size of a legend key in R?

To change the Size of Legend, we have to add guides() and guide_legend() functions to the geom_point() function. Inside guides() function, we take parameter color, which calls guide_legend() guide function as value. Inside guide_legend() function, we take an argument called override.

How do I add a legend in ggplot2?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.


2 Answers

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

like image 66
metasequoia Avatar answered Sep 29 '22 02:09

metasequoia


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) 
like image 32
Matt Parker Avatar answered Sep 29 '22 01:09

Matt Parker