简体   繁体   中英

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?

替代文字

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

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)

...当我偶然发现这个较老的线程时,也许有必要添加你需要加载library("scales") ,否则你会收到以下错误信息

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM