Add a text to each ggplot facet showing the sd() of y

A plot:

library(tidyverse)
diamonds |> 
  filter(x > 0) |> 
  ggplot(aes(x = x, y = log(price))) +
  geom_point() +
  facet_wrap(. ~ cut)

I would like to show in each facet a single text over lay data point with the standard deviation of log(price).

E.g.

diamonds |> 
  filter(x > 0) |> 
  group_by(cut) |> 
  summarise(sd_log_price = sd(log(price)))

# A tibble: 5 × 2
  cut       sd_log_price
  <ord>            <dbl>
1 Fair             0.766
2 Good             0.982
3 Very Good        1.04 
4 Premium          1.03 
5 Ideal            0.992

Is there a way I can overlay each corresponding sd() and facet?

Is this the sort of thing you are looking for?

library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.2

STATS <- diamonds |> 
  filter(x > 0) |> 
  group_by(cut) |> 
  summarise(sd_log_price = sd(log(price))) |> 
  mutate(sd_log_price = round(sd_log_price,4))

diamonds |> 
  filter(x > 0) |> 
  ggplot(aes(x = x, y = log(price))) +
  geom_point() +
  geom_text(aes(x=9,y=7,label= sd_log_price), data = STATS)+
  facet_wrap(. ~ cut)

Created on 2022-02-09 by the reprex package (v2.0.1)

1 Like

Perfect, thanks a lot!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.