【问题标题】:plot unique groups in R by time period按时间段绘制 R 中的唯一组
【发布时间】:2019-10-21 02:03:33
【问题描述】:
mydat=structure(list(date = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 2L), .Label = c("01.01.2018", "02.01.2018"), class = "factor"), 
    x = structure(c(2L, 2L, 2L, 3L, 1L, 1L, 1L, 1L, 1L), .Label = c("e", 
    "q", "w"), class = "factor"), y = structure(c(2L, 2L, 2L, 
    3L, 1L, 1L, 1L, 1L, 1L), .Label = c("e", "q", "w"), class = "factor")), .Names = c("date", 
"x", "y"), class = "data.frame", row.names = c(NA, -9L))

我们可以看到 xy 是组变量(我们只有组类别 q-q,w-w,e-e)

1 月 1 日

q   q = count 3
w   w =count 1

然后是 1 月 2 日

e e =count 5

如何在图表中显示类别计数:数据集很大,因此需要 1 月份的图表,因此图表按天显示已售类别的数量

【问题讨论】:

    标签: r ggplot2 dplyr tidyr


    【解决方案1】:

    我发现你的问题不太清楚,但也许这会有所帮助:

    library(lubridate) # manipulate date
    library(tidyverse) # manipulate data and plot
     # your data
     mydat %>%
     # add columns (here my doubts)
     mutate(group = paste (x,y, sep ='-'),                        # here the category pasted
            cnt = ifelse(paste (x,y, sep ='-') == 'q-q',3,
                   ifelse(paste (x,y, sep ='-') == 'w-w',1,5)),   # ifelse with value
            day = day(dmy(date))) %>%                             # day
    group_by(group,day) %>%                                       # grouping
    summarise(cnt = sum(cnt)) %>%                                 # add the count as sum
    # now the plot, here other doubts on your request  
    ggplot(aes(x = as.factor(day), y = cnt, group = group, fill = group, label = group)) +
      geom_bar(stat = 'identity', position = 'dodge') +
      geom_label(position = position_dodge(width = 1)) + 
      theme(legend.position="none")
    

    【讨论】:

    • 我可以再问你一个问题吗?我编辑了帖子。这里是聚合数据集 (q) ,其中度量变量是价格,它是使用 sum 函数按日期、x 和 y 聚合的。如何获取x 轴上的日期和y 轴上的x+y 组以及每个组x+y 价格线的绘图。或者我应该打开新话题?
    • 恕我直言,您可以提出一个新问题,但我的建议是尝试自己动手,学习如何绘图:一些小提示(这是对上面代码的未经测试的调整),@987654327 @.
    【解决方案2】:

    你的问题不像我希望的那样干净,但我想你想知道我们每天每个小组有多少,对吧?

    您可以使用dplyr 包中的group_by

    我创建了一个名为 group 的新变量,它包含 xy

    
    mydata <- mydat %>%
      mutate('group' = paste(x, y, sep = '-')) %>%
      group_by(date, group) %>%
      summarise('qtd' = length(group))
    
    

    结果:

    date       group   qtd
    01.01.2018 q-q       3
    01.01.2018 w-w       1
    02.01.2018 e-e       5
    

    您可以使用ggplot2 包并创建如下,您可以使用facet_wrap 按日期分隔图:

    ggplot(data = mydata, aes(x = group, y = qtd)) +
      geom_bar(stat = 'identity') +
      facet_wrap(~date)
    

    否则,您可以使用ggplot2 的另一种语法并使用fill。如果你有很多约会,有时会更好。

    代码

    ggplot(data = mydata, aes(x = group, y = qtd, fill = date)) +
      geom_bar(stat = 'identity')
    

    祝你好运!

    【讨论】:

      猜你喜欢
      • 2020-04-07
      • 2015-07-18
      • 2021-12-15
      • 1970-01-01
      • 2021-12-19
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多