Reputation: 16050
I want to create a bar plot based on the following data:
Station Delay
A 5
B 6
A 4
A 3
B 8
X axis should contain stations "A" and "B", while bars (Y axis) should show average delay per a station.
I tried this, but it does not give a correct result:
barplot(c(data$Station, data$Delay),
main="BARPLOT", xlab="Stations", ylab="Delays",
names.arg=data$Station)
Upvotes: 2
Views: 19146
Reputation: 1867
df <- data.frame(Station = c("A", "B", "A", "A", "B"), Delay= c(5, 6, 4, 3, 8))
library(dplyr)
df <- df %>% group_by(Station) %>% summarise(me = mean(Delay))
library(ggplot2)
ggplot(aes(x = Station, y = me), data = df) + geom_bar(stat = "identity")
or directly with stat_summary
ggplot(aes(x = Station, y = Delay), data = df) + stat_summary(fun.y = "mean", geom = "bar")
Upvotes: 4
Reputation: 24074
In base R, you can do:
m_data <- data.frame(data$Station, m_del=ave(data$Delay, data$Station), stringsAsFactors=F)
barplot(unique(m_data)$m_del, names=unique(m_data)$Station, main="BARPLOT", xlab="Stations", ylab="Delays")
Or with the package data.table
, you can do:
library(data.table)
m_data <- setDT(data)[, mean(Delay), by=Station]
m_data[, barplot(V1, names=Station, main="BARPLOT", xlab="Stations", ylab="Delays")]
Upvotes: 1