I am practicing with the "diamonds" dataset in ggplot 2. I am trying to make a bar chart plot, to demonstrate the average price per color category:
This is the code I wrote:
ggplot(data=diamonds)+
geom_bar(mapping=aes(x=color,y=price),
fun="mean",stat="summary",fill="yellow")+
geom_text(
aes(label=scales::comma(
round(mean(price),digits=3)
),
x=color,y=price),
stat="summary",size=3,
vjust=-1)
The visualization being generated by this code is shown as follow:
The problems that I have encountered are regarding the data labels:
- the data labels in each bar are the same. this is obviously not correct;
- why wouldn't my function "digitals=3" work? Why could not change how many digits to show in the data labels?
I have searched online for possible answers, but could not find a good solution
The first issue is that using
mean(price)you compute the overall mean ofprice. To get the mean percolorwhich is computed bystat_summaryand which you display as bars you have to uselabel = after_stat(y). Hereyis the variable which contains the values computed bystat_summaryunder the hood. This value is automatically mapped on theyaesthetic. However, to use it for thelabelwe have to wrap inafter_statto access the computed value.Second, the issue is that you wrapped
roundinscales::commawhich will round the alreadyrounded value a second time with a defaultaccuracy=1. To fix that I would suggest to use theaccuracyargument ofscales::comma, e.g. set it to.001to round to three decimals.