【问题标题】:Representing time series data based on multiple classifications in R在 R 中表示基于多个分类的时间序列数据
【发布时间】:2017-09-14 18:08:55
【问题描述】:

所以这是我在 SO 中的第一篇文章。 我有一个数据集,如下所示。但它适用于更多的桶和更长的时间段。我正在寻找某种交互式绘图,非常适合表示这些数据。表示需要考虑到所有提到的列并且需要是交互式的。我尝试通过 dygraphs、ggplot2、rcharts 和其他一些包,但没有找到任何简单方便的东西。我刚从 R 开始,所以一些见解会很棒。

Month    Age    Gender  Percentage
Mar-16  0-20    F         1.01
Mar-16  0-20    M         0.46
Mar-16  21-30   F         5.08
Mar-16  21-30   M         4.03
Apr-16  0-20    F         2.34
Apr-16  0-20    M         3.55
Apr-16  21-30   F         6.78
Apr-16  21-30   M         9.08
May-16  0-20    F         3.56
May-16  0-20    M         3
May-16  21-30   F         2.08
May-16  21-30   M         10

【问题讨论】:

  • 您可以使用 ggplotly & ggplot2,并按年龄分组,按性别着色,然后您可以绘制 x= 月和 y = 百分比。 ggplotly 会给你想要的互动。其中 ggplot2 将创建创建绘图的好方法

标签: r time-series dygraphs rcharts htmlwidgets


【解决方案1】:

这是 ggplot2 的快速可视化,并按照@KppatelPatel 的建议进行了绘图 ggplotly 的输出将是图形用户界面上的交互式绘图,带有悬停信息,例如Month: Apr-16; Percentage: 2.34; Gender: F

library(ggplot2)
library(plotly)

p <- ggplot(dat, aes(x=Month, y=Percentage, fill=Gender)) + 
  geom_bar(stat="identity", position = position_dodge()) + 
  facet_wrap(~Age, ncol=2)

ggplotly(p)

所提供数据的data.frame dput:

dat <- structure(list(Month = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 1L, 
1L, 3L, 3L, 3L, 3L), .Label = c("Apr-16", "Mar-16", "May-16"), class = "factor"), 
Age = structure(c(1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 
2L, 2L), .Label = c("0-20", "21-30"), class = "factor"), 
Gender = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 2L), .Label = c("F", "M"), class = "factor"), Percentage = c(1.01, 
0.46, 5.08, 4.03, 2.34, 3.55, 6.78, 9.08, 3.56, 3, 2.08, 
10)), .Names = c("Month", "Age", "Gender", "Percentage"), class = "data.frame", row.names = c(NA, 
-12L))

编辑:

要按逻辑顺序绘制时间,请将月份转换为日期格式:

library(dplyr)
dat$Time <- dat$Month %>% 
            as.character %>%
            paste("01-", .) %>%
            as.Date(., format= "%d-%b-%y")

使用x=Time 为上面相同的 ggplot 绘图将为您提供以下信息:

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2015-06-28
    • 2011-02-25
    • 2021-04-20
    相关资源
    最近更新 更多