1

I have a dataset called Flt

CARRIER   CANCELLED  DIVERTED
 UA          0          0
 UA          1          0
 UA          0          1
 AA          1          0
 AA          0          0
 DL          0          1
 DL          1          0

I want to do a barplot like this enter image description here

Thing is I just want Cancelled =1 and Diverted=1 in the barplot. I tried using ggplot but I am not sure on how to add the second column.

ggplot(data=Flt) + geom_bar(aes(x=CARRIER, fill=c(CANCELLED=1),(DIVERTED=1)),position = "dodge")

I get error "stat_count() can only have an x or y aesthetic" when I use the code above. Any help would be greatly appreciated.

2 Answers 2

1

You're looking for geom_col:

pivot_longer(df,2:3) %>% 
  ggplot() + geom_col(aes(x=CARRIER,y=value,fill=name), position="dodge")

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe are you looking for this:

library(dplyr)
library(tidyr)
library(ggplot2)
#Code
df %>% pivot_longer(-CARRIER) %>%
  filter(value==1) %>%
  group_by(CARRIER,name) %>% summarise(N=sum(value))%>%
  ggplot(aes(x=CARRIER,y=N,fill=name))+
  geom_bar(stat = 'identity',position = position_dodge2(0.9,preserve = 'single'),color='black')

Output:

enter image description here

Or this:

#Code2
df %>% pivot_longer(-CARRIER) %>%
  group_by(CARRIER,name) %>% summarise(N=sum(value==1))%>%
  ggplot(aes(x=CARRIER,y=N,fill=name))+
  geom_bar(stat = 'identity',position = position_dodge(0.9),color='black')

Output:

enter image description here

Some data used:

#Data
df <- structure(list(CARRIER = c("UA", "UA", "UA", "AA", "AA", "DL", 
"DL"), CANCELLED = c(0L, 1L, 0L, 1L, 0L, 0L, 1L), DIVERTED = c(0L, 
0L, 1L, 0L, 0L, 1L, 0L)), class = "data.frame", row.names = c(NA, 
-7L))

1 Comment

Your #code2 logic is what I need for another thing I am working on. But i dont understand group_by() and summarize(). The other thing I need is to plot various airports vs dep_delay and arr_delay but it should only count (Diverted = 0) and (Cancelled = 0). I am wondering how will you introduce condition in the code. I tried to put in summarize() but I get error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.