`ggplot2`: barplot label values ​​that use` fun.y = "mean` `` stat_summary`

If I use ggplot2 stat_summary() to make a barcode of the average number of miles per gallon for 3-, 4- and 5-speed cars, for example, how can I mark each column with the average value for mpg?

 library(ggplot2) CarPlot <- ggplot() + stat_summary(data= mtcars, aes(x = factor(gear), y = mpg, fill = factor(gear) ), fun.y="mean", geom="bar" ) CarPlot 

I know that you can usually use geom_text() , but it's hard for me to figure out what to do to get the average from stat_summary() .

+6
source share
2 answers

You can use the ..y.. internal variable to get the calculated value.

enter image description here

 library(ggplot2) CarPlot <- ggplot(data= mtcars) + aes(x = factor(gear), y = mpg)+ stat_summary(aes(fill = factor(gear)), fun.y=mean, geom="bar")+ stat_summary(aes(label=round(..y..,2)), fun.y=mean, geom="text", size=6, vjust = -0.5) CarPlot 

but it’s probably better to aggregate in advance.

+12
source

I would simply precompile the statistics and subsequently build a graph:

 library(plyr) library(ggplot2) dat = ddply(mtcars, .(gear), summarise, mean_mpg = mean(mpg)) dat = within(dat, { gear = factor(gear) mean_mpg_string = sprintf('%0.1f', mean_mpg) }) ggplot(dat, aes(x = gear, y = mean_mpg)) + geom_bar(aes(fill = gear), stat = "identity") + geom_text(aes(label = mean_mpg_string), vjust = -0.5) 

enter image description here

+5
source

Source: https://habr.com/ru/post/958626/


All Articles