Mostafa90
Mostafa90

Reputation: 1706

Plot a histogram with ggplot of mean of a variable in function of another varable's observation

I will give an simple example to illustrate my issue.

dura <- c(158, 21, 451, 157, 963, 485, 211, 154, 1454, 475)
tel <- c("nokia", "apple", "samsung", "lg", "samsung", "lg", 
         "apple", "motorola", "samsung", "huawei")
color <- c("blue", "orange", "white", "green", "black", "blue", 
          "yellow", "green", "red", NA)
df <- data.frame(dura, tel, color)

For example here, I want to have the mean of duration for eatch tel as histogram plot? I don't know if I have to use the apply functions or ggplot do it directly?

t1 <- tapply(df$dura,df$tel, mean)
barplot(t1, horiz=F,main="Durée selon la marque de téléphone", 
        ylab = "Durée moyenne (ms)", cex.names = 0.6, las = 2, col =    "orange")

Is it possible with ggplot?

Upvotes: 0

Views: 72

Answers (1)

Roland
Roland

Reputation: 132696

This includes calculation of the mean in the ggplot2 code:

library(ggplot2)
ggplot(df, aes(x = tel, y = dura)) +
  stat_summary(fun.y = mean, geom = "bar", fill = "orange") +
  theme_bw()

Read ggplot2 tutorials to learn more about it.

Upvotes: 2

Related Questions