umar
umar

Reputation: 45

Plotting more than 2 factor variables in ggplot

My dataset looks like below,

dat <- data.frame(ID = c(150,151,155,155,155,155,150), year = c(1995,2011,2012,2012,2013,2012,2013), Acceptance = c(no,yes,yes,yes,yes,no,no));

I wanted to plot a bar chart, for ID 155, with X-axis over the Year, and var 3 Which shows only Yes.

I have tried the below code

cl_d <- dat %>%
  filter(ID==155)%>%
  filter(year(Date)>2000)%>%
  group_by(ID, year)%>%
  summarise(count=n())

ggplot(cl_d, aes(year, count))+
  geom_bar(stat='identity')

The bar plot should show the count of Acceptance for "Yes" over the Date greater than 2000 for the particular ID 155

Upvotes: 0

Views: 86

Answers (4)

Maurits Evers
Maurits Evers

Reputation: 50668

Is this what you're after?

library(tidyverse);
dat %>%
    filter(ID == 155 & year >= 2000 & Acceptance == "yes") %>%
    count(ID, year) %>%
    ggplot(aes(as.factor(year), n)) +
    geom_bar(stat = "identity") +
    labs(x = "Year", y = "Count")

enter image description here


Sample data

dat <- data.frame(
    ID = c(150,151,155,155,155,155,150),
    year = c(1995,2011,2012,2012,2013,2012,2013),
    Acceptance = c("no","yes","yes","yes","yes","no","no"));

Upvotes: 1

Amar
Amar

Reputation: 1373

It appears you want year to be in date format and the graph to also be in the date format. If this is the case see the code below:

dat <- data.frame(ID = c(150,151,155,155,155,155,150), 
 year =  c(1995,2011,2012,2012,2013,2012,2013), 
 Acceptance = c("no","yes","yes","yes","yes","no","no"))

dat$year <- as.Date(ISOdate(dat$year, 1, 1))

cl_d <- dat %>% filter(ID==155) %>%
  subset(year > as.Date("2000-01-01")) %>%
         group_by(ID, year) %>%
         summarise(count=n())

ggplot(cl_d, aes(year, count)) + 
  geom_bar(stat='identity') + 
  scale_x_date(date_labels ="%Y", date_breaks = "1 year")

Upvotes: 1

Roman
Roman

Reputation: 17648

This?

dat %>%
  filter(ID==155)%>%
  filter(Acceptance == "yes") %>% 
  filter(year>2000) %>% 
  group_by(year) %>% 
  count() %>% 
 ggplot(aes(year, n))+
   geom_col()

enter image description here

Upvotes: 1

Boetzka
Boetzka

Reputation: 13

Hey this code should work I alway try to avoid plugins if you have any questions left just ask!

dat <- data.frame(c(150,151,155,155,155,155,150), 
c(1995,2011,2012,2012,2013,2012,2013), 
c("no","yes","yes","yes","yes","no","no"))
colnames(dat)[1] <- "ID"
colnames(dat)[2] <- "Date"
colnames(dat)[3] <- "claim_count1"
NewData <- dat[dat$ID==155 & dat$Date > 2000 & dat$claim_count1== "yes",]
ggplot(data=NewData, aes(x=Date)) + geom_bar(stat ="count")

Upvotes: 1

Related Questions