按时间段绘制R中的唯一组

时间:2019-06-05 14:27:41

标签: r ggplot2 dplyr tidyr

.env.production

我们可以看到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)) x是组变量(我们只有组类别q-q,w-w,e-e)

1月1日

y

然后在1月2日

q   q = count 3
w   w =count 1

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

enter image description here

2 个答案:

答案 0 :(得分:2)

我发现您的问题不太清楚,但这也许可以帮助您

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

enter image description here

答案 1 :(得分:1)

您的问题并不是我所希望的那么干净,但是我想您想知道我们每一天中有多少人,对吗?

您可以使用group_by包中的dplyr

我创建了一个名为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)

enter image description here

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

代码

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

enter image description here

祝你好运!