Alan Medina
Alan Medina

Reputation: 31

How to add trailing zeros for cents and a dollar sign ($) to the Y-axis using ggplot2?

I would like to have dollar amounts on the y-axis with a dollar sign ($) and 2 trailing zeros to indicate cents (for example, $1.00).

I have the following code and the resultant plot.

library(ggplot2)
library(scales)
df <- data.frame("x" = c("A1",
                         "A2",
                         "A3"),
                 "y" = c(0.77,5.42,8.06))

ggplot()+
  geom_bar(data=df, aes(x, y), stat="identity")+
  theme_minimal()+
  scale_y_continuous(minor_breaks = seq(0 , 9, 1.00),
                     breaks=c(seq(0,9,1.00)),label=dollar, 
                     expand = c(.01, 0), limits = c(0, 9))

enter image description here

Upvotes: 3

Views: 480

Answers (2)

r2evans
r2evans

Reputation: 160687

It appears you're already using the scales package for dollar, there is also a dollar_format function made for this.

ggplot()+
  geom_bar(data=df, aes(x, y), stat="identity")+
  theme_minimal()+
  scale_y_continuous(minor_breaks = seq(0 , 9, 1.00),
                     breaks=c(seq(0,9,1.00)),label=dollar_format(accuracy=0.01), 
                     expand = c(.01, 0), limits = c(0, 9))

enter image description here

(If you look at the source for dollar_format, it's effectively just a mechanism to set arguments for dollar (e.g., accuracy, scale, prefix) and have that return something appropriate for label=, as in a function.)

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 389175

You can use sprintf to format y-axis :

library(ggplot2)

ggplot()+
  geom_bar(data=df, aes(x, y), stat="identity")+
  theme_minimal()+
  scale_y_continuous(minor_breaks = seq(0 , 9, 1.00),
                     breaks=c(seq(0,9,1.00)),
                     label= function(x) sprintf('$%.2f', x)
                     expand = c(.01, 0), limits = c(0, 9))

enter image description here

Upvotes: 2

Related Questions