psysky
psysky

Reputation: 3195

plot unique groups in R by time period

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

As we can see x and y are groups varibles (we have only the group categories q-q,w-w,e-e)

for 1 january

q   q = count 3
w   w =count 1

then for 2 january

e e =count 5

How count of categories display in graph like this: dataset is large so graph needed for january month, so the plot display number of sold categories by day

enter image description here

Upvotes: 1

Views: 177

Answers (2)

Your question isn't too much clean as I wish, but I think you wanna to find how much of each group we have in each day, right?

You can use group_by from dplyr package.

I created a new variable called group which contatenate x and y.


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

Result:

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

You can use ggplot2 package and create as below where you can use facet_wrap to separate the plots by date:

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

enter image description here

Otherwise you can use another syntax of ggplot2 and use fill. It's better sometimes specially if you have a lot of dates.

Code:

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

enter image description here

Good luck!

Upvotes: 1

s__
s__

Reputation: 9485

I've found your question not too much clear, but maybe this could help:

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

Upvotes: 2

Related Questions