Facet_Wrap + Median & Mean


I'm trying to put Mean and Median using Facet_Wrap but it's not working I already searched but didn't find the answer can someone please help me?

p <- ggplot(data = BD_Ativos, aes(x = BD_Ativos$`Annual Gross Salary`)) + geom_histogram(binwidth = 1000)
p + facet_wrap(~BD_Ativos$Business, ncol = 3)

After this how can I put Mean and Median for each histogram?

Thanks in advance

First thing is that when you pass a dataframe into ggplot as a data argument, later when you want to refer to variables from it , you just name the variables, you don't restate the dataframe name and use $ syntax.

1 Like

Thanks for the fast reply.

I'm new using R.

And I didn't understand well, sorry

Can you please explain me again in another way?

Here is one method. Notice that in ggplot I just use the column names Business and Gross_Salary. I do not write DF$Business or DF$Gross_Salary.

#invent some data
DF <- data.frame(Business = rep(c("A", "B", "C"), each = 10),
                 Gross_Salary = c(rnorm(10, 50, 10), rnorm(10, 40, 10), rnorm(10, 60, 10)))
library(dplyr, warn.conflicts = FALSE)
STATS <- DF %>% group_by(Business) %>% 
  summarize(Avg = mean(Gross_Salary), Median = median(Gross_Salary)) %>% 
  pivot_longer(Avg:Median, names_to = "Stat", values_to = "Value")
#> `summarise()` ungrouping output (override with `.groups` argument)
ggplot(DF, aes(x = Gross_Salary)) + geom_histogram(binwidth = 5) + 
  facet_wrap(~Business) +
  geom_vline(data = STATS, mapping = aes(xintercept = Value, color = Stat))

Created on 2021-02-25 by the reprex package (v0.3.0)

Many thanks for your help!

I'm a newbie in R.

This topic was automatically closed 21 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.