ZachW
ZachW

Reputation: 19

How to Visualize The frequency of a categorical variable in R

I have 2 variables in my dataframe that I am trying to use ggplot to graph. On the x-axis I want the date which has a daily frequency. On the y-axis I want the count of unique names that show up on that given day.

The variables look something like this in the dataframe.

     Date           Name

1   2016-03-01      Joe
2   2016-03-01      Joe
3   2016-03-01      Joe 
4   2016-03-01      Mark
5   2016-03-01      Sue
6   2016-03-02      Mark    
7   2016-03-02      Joe
8   2016-03-03      Joe
9   2016-03-03      Joe
10  2016-03-03      Bill

So the frequency on the y-axis on the first day would show 3, 2 on the second, and 2 on the third.

My question is how do I produce that graph.

Upvotes: 0

Views: 969

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

count number of unique Name for each Date and then plot with geom_bar/geom_col.

library(dplyr)
library(ggplot2)
df %>%
  group_by(Date) %>%
  summarise(n = n_distinct(Name)) %>%
  ggplot()  + geom_col(aes(Date, n))
  #ggplot() + geom_bar(aes(Date, n), stat = "identity")

enter image description here

data

df <- structure(list(Date = c("2016-03-01", "2016-03-01", "2016-03-01", 
"2016-03-01", "2016-03-01", "2016-03-02", "2016-03-02", "2016-03-03", 
"2016-03-03", "2016-03-03"), Name = c("Joe", "Joe", "Joe", "Mark", 
"Sue", "Mark", "Joe", "Joe", "Joe", "Bill")), class = "data.frame",
 row.names = c(NA, -10L))

Upvotes: 1

Related Questions