Reputation: 41
I have created a scatter plot using packages ggplot2 and scales. I can get the plot to EITHER have a Y axis beginning at zero OR have a y axis formatted as a currency value. I cannot get it do to both.
This code correctly formats the Y scale to O, but expresses the Y scale in notational form:
age_chart %>% ggplot(aes(x = `Patient Age`, y=Total))+
geom_point(alpha = .5)+
geom_smooth()+
xlab('Age')+
ylab('Total Plan Pmt')+
ggtitle('Total Plan Payment by Patient Age')+
scale_y_continuous(labels = dollar_format(prefix="$"))+
theme(plot.title = element_text(hjust = 0.5))+
ylim(0,NA)
If I comment out the last row the plot correctly formats the Y scale as currency, but has a minimum value below 0.
age_chart %>% ggplot(aes(x = `Patient Age`, y=Total))+
geom_point(alpha = .5)+
geom_smooth()+
xlab('Age')+
ylab('Total Plan Pmt')+
ggtitle('Total Plan Payment by Patient Age')+
scale_y_continuous(labels = dollar_format(prefix="$"))+
theme(plot.title = element_text(hjust = 0.5))+
#ylim(0,NA)
Question: How can I create a Y axis beginning at 0 and formatted as currency? Thanks you.
Upvotes: 0
Views: 682
Reputation: 38023
TL;DR:
Use the following:
scale_y_continuous(labels = dollar_format(prefix="$"), limits = c(0,NA)
and leave out
ylim(0,NA)
Longer answer:
There are multiple ways for ggplot to handle limits on positional scales.
xlim()
or ylim()
scale_x/y_continuous()
or discrete, or datetime etc.coord_*(xlim = ..., ylim = ...)
However, if you supply multiple to ggplot, it doesn't know which one the user wants and picks the last one of scale_x/y_continous
and xlim/ylim
. These limits affect how things are drawn, i.e. everything that is out of bounds will be censored by default. coord_*()
works differently and affects what is drawn, it doesn't censor but can clip datapoints that are outside of panel limits.
Now in your case specifically, the plot forgets what it learned about the y-axis (labels = dollar_format(prefix="$")
) because you supplied a new argument for the y-axis (ylim
), replacing the old one. If you find running into this problem frequently, I would suggest to use the more verbose scale_x/y_continuous/discrete()
option by default.
Upvotes: 1