如何创建条形图并显示平均Y值

时间:2015-10-13 07:37:30

标签: r bar-chart

我想根据以下数据创建条形图:

Station    Delay
A          5
B          6
A          4
A          3
B          8

X轴应包含“A”和“B”站,而条形(Y轴)应显示每个站的平均延迟。

我试过这个,但它没有给出正确的结果:

barplot(c(data$Station, data$Delay), 
        main="BARPLOT", xlab="Stations", ylab="Delays", 
        names.arg=data$Station)  

2 个答案:

答案 0 :(得分:1)

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")

enter image description here

或直接使用stat_summary

ggplot(aes(x = Station, y = Delay), data = df) + stat_summary(fun.y = "mean", geom = "bar")

答案 1 :(得分:1)

在基地R,你可以这样做:

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")

或者使用包data.table,您可以执行以下操作:

library(data.table)
m_data <- setDT(data)[, mean(Delay), by=Station]
m_data[, barplot(V1, names=Station, main="BARPLOT", xlab="Stations", ylab="Delays")]

enter image description here