ggplot时间序列的条形图

时间:2015-02-17 08:13:08

标签: r ggplot2

我正在阅读Hadley Wickham关于ggplot的书,但我很难在条形图中绘制一定的权重。以下是示例数据:

dates <- c("20040101","20050101","20060101")
dates.f <- strptime(dates,format="%Y%m%d")

m <- rbind(c(0.2,0.5,0.15,0.1,0.05),c(0.5,0.1,0.1,0.2,0.1),c(0.2,0.2,0.2,0.2,0.2))
m <- cbind(dates.f,as.data.frame(m))

此data.frame在第一列中包含日期和每行相应的权重。我想使用“填充”参数在条形图中绘制每年的权重。

我可以使用:

将权重绘制为条形图
p <- ggplot(m,aes(dates.f))
p+geom_bar()

然而,这并不是我想要的。我想在每个酒吧看到每个重量的贡献。而且,我不明白为什么我在x轴上有奇怪的格式,即显示“2004-07”和“2005-07”的原因。

感谢您的帮助

2 个答案:

答案 0 :(得分:9)

希望这就是你要找的东西:

ggplot2需要长格式的数据。

require(reshape2)
m_molten <- melt(m, "dates.f")

绘图本身由

完成
ggplot(m_molten, aes(x=dates.f, y=value, fill=variable)) + 
  geom_bar(stat="identity")

enter image description here

如果您愿意并排,可以将position="dodge"添加到geom_bar

修改

如果您只想要每年休息一下:将m_molten$dates.f转换为日期。

require(scales)
m_molten$dates.f <- as.Date(m_molten$dates.f)

ggplot(m_molten, aes(x=dates.f, y=value, fill=variable)) + 
  geom_bar(stat="identity") + 
  scale_x_date(labels = date_format("%y"), breaks = date_breaks("year"))

P.S。:有关哈德利整洁数据的哲学,请参阅http://vita.had.co.nz/papers/tidy-data.pdf

答案 1 :(得分:2)

要创建所需的绘图,您必须将数据从“宽”重塑为“高”。有很多方法可以做到这一点,包括基础R中的reshape()函数(不推荐),reshape2tidyr

tidyr包中,您有两个重塑数据的功能,gather()spread()

函数gather()从宽变为高。在这种情况下,您必须收集列V1:V5

试试这个:

library("tidyr")

tidy_m <- gather(m, var, value, V1:V5)

ggplot(tidy_m,aes(x = dates.f, y=value, fill=var)) +
  geom_bar(stat="identity")

enter image description here