【问题标题】:ggplot bar chart for time series时间序列的ggplot条形图
【发布时间】:2025-12-25 17:00:12
【问题描述】:

我正在阅读 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”。

感谢您的帮助

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    希望这是您正在寻找的:

    ggplot2 需要长格式的数据。

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

    绘图本身由

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

    如果需要,您可以将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,了解 Hadley 的整理数据哲学。

    【讨论】:

    • 也许是一个小问题:我想通过scale_x_date(lables=date_format("%y")) 更改标签。这给出了一个错误,它无法找到函数 date_format。如何只显示 04、05、06?
    【解决方案2】:

    要创建您需要的绘图,您必须将数据从“宽”重塑为“高”。有很多方法可以做到这一点,包括 base 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")
    

    【讨论】: