Ggplot2 geom_boxplot: annotating counters without calculating them in advance

I want to add annotations, such as n=5, n=4with the number of data points in each square at the top edge of my graph geom_boxplot.

I know that I can do this with geom_textpre-calculated calculations, but it seems that ggplot2having all these wonderful binning and summarizing functionality, should I be able to do it myself?

Suppose we have this data:

library(tidyverse)

dd = tribble(
    ~val, ~kind,
    1,    'A',
    3,    'A',
    5,    'A',
    5,    'A',
    6,    'A',
    3,    'B',
    4,    'B',
    4,    'B',
    5,    'B'
)

I tried this:

> base = ggplot(dd, aes(x=kind, y=val)) + geom_boxplot()
> base + geom_text(y=6, label=..count.., stat='count')

Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomText,  : 
  object '..count..' not found

Presumably geom_textjust ignored my parameter stat?

Next I tried this:

> base + stat_count(aes(y=6, label=..count..), geom='text')

Error: stat_count() must not be used with a y aesthetic.

Isn't that my problem, can I do something useful with the result ..count.., “y aesthetic” or not?

.
- , ggplot2 ?
- ggplot2, ?

+1
1

ggplot2. , , , -. , : . ggplot2 . , stat, geom. , ..variable.. , stat, .

, , y geom_text stat_count .

, , - , . , ggstance. , . stat_density(), "x" (.. , ) y "y" (.., ) x. stat_xdensity(), stat_density(), , x y.

, ggplot2, , layer() -type, : . I.e, - :

layer2(aes_geom(y = ..x.., x = ..y..),
       aes_stat(x = variable),
       geom = "line", stat = "density")

( , .)

, , , aes . , , . :

ggplot(iris, aes(x = Species, y = Sepal.Length)) + 
  geom_boxplot() +
  geom_point(aes(x = Species, y = median(Sepal.Length)), size = 3, color = "red")

:

enter image description here

, .

+1

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


All Articles