2

Note: This question is a duplicate, but there's an additional solution below that wasn't given in the original question, and might be more useful in some cases.

I am trying to create a series of bar charts from data which have a number of repeats for each category - here is a small reproducible example. What I want is the bar chart to show the average of concs for each bleach_time. When plotting the bar chart straight from df the sum of all concs is shown on the bar chart.

library(ggplot2)

bleach_time <- c(0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24)
conc <- c(23, 54, 12, 96, 34, 65, 34, 22, 35, 06, 90, 69)
df <- data_frame(bleach_time, conc)

df_p <- ggplot(df, aes(as.factor(bleach_time), conc))

df_p + geom_bar(stat = "identity", na.rm = TRUE)

Bar chart with sum of all data

I can create a summary data frame of the averages for each bleach time then replot the bar chart with df_av, but I would prefer not to have to add in this additional step and data frame as the data frames I'm working with are very large and I have a lot of plots to draw. Is there a way I can choose the average of concs in the call to plot?

library(dplyr)
df_av <- df %>% group_by(bleach_time) %>% summarise_all(mean)
Lucy Wheeler
  • 271
  • 3
  • 17
  • 1
    Re: the duplicate comment you edited in - don't worry; questions closed as duplicates are not automatically deleted by the system because they serve as signposts for future viewers. This question (and answer) will stick around unless the community (site users and/or moderators, not the "Community user") votes to manually delete the question. – TylerH Apr 05 '18 at 15:20

2 Answers2

3

Try this one,

df_p + stat_summary(fun.y = mean, geom = "bar", na.rm = TRUE)
TheRimalaya
  • 4,232
  • 2
  • 31
  • 37
2

Never mind, I found a solution! stat = "summary", fun.y = "mean" returns the average of each category.

Lucy Wheeler
  • 271
  • 3
  • 17