Home > database >  How can I plot the mean of a feature in a barplot?
How can I plot the mean of a feature in a barplot?

Time:01-27

I have followed barplot example:

library(ggplot2)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")

g <- ggplot(df, mapping = aes(forcats::fct_infreq(sex), fill = as.factor(size)))  
  geom_bar(colour = "white")   coord_flip()   
  geom_text(aes(label = paste0("n=", ..count..)), stat='count', 
            position = position_stack(vjust = 0.5))
g

Which gives me:

enter image description here

What I want is the mean of the size from the Female and the Male:

enter image description here

CodePudding user response:

To get the mean of values by size, you could create a mean column first,

df %>% 
  group_by(sex) %>% 
  mutate(mean = mean(size)) %>% 
  ungroup() %>% 
  ggplot(aes(fct_infreq(sex)))  
  geom_bar(aes(fill = as.factor(size)), colour = "white")   
  geom_text(aes(label = sprintf("mean = %.2f",mean)), stat="count", position = position_stack(vjust = 0.5))  
  coord_flip()

enter image description here


Previous answer: When you set the aesthetics with aes inside the ggplot function, it will affect all future geom_ commands, but here you should not use the same aes for geom_bar and geom_text:

ggplot(df, aes(fct_infreq(sex)))  
  geom_bar(aes(fill = as.factor(size)), colour = "white")   
  geom_text(aes(label = paste0("mean=", ..count..)), stat="count", position = position_stack(vjust = 0.5))  
  coord_flip()
  •  Tags:  
  • Related