barplot discrete variables for 2 groups

barplot discrete variables for 2 groups



I have a dataframe with a column of 'Y' or 'N' for 2 groups eg:


drug<-c("Y","Y","N","Y","Y","Y","N","N","N","N","N","Y","Y","Y","N","N")
group<-c(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1)
df<-data.frame(drug,group)



I want to make barplots of the 'Y'/'N' for both groups with the two groups beside each other.
I've tried various things with ggbarplot and get weird plots out


ggbarplot(my_matches, x = "group", y = "drug",
color = "group", palette = c("#00AFBB", "#FC4E07"))



and have tried making tables and plotting these as barplots like


counts0<-df[which(df$group==0),]
counts1<-df[which(df$group==1),]

grp0<-table(counts0$drug)
grp1<-table(counts1$drug)
s<- as.data.frame(t(rbind(grp0,grp1)))

barplot(s$grp0, s$grp1,beside=T)



As you can tell, I'm a beginner and have been driving myself mad trying to solve this. Please help!





What's my_matches ? It's not defined anywhere.
– neilfws
Aug 30 at 5:02


my_matches




1 Answer
1



First, there's no need to create vectors as data frame columns, and df is not a great variable name (there's a function of the same name). Create your data frame in one step like this:


df


mydata <- data.frame(drug = c("Y","Y","N","Y","Y","Y","N","N","N","N","N","Y","Y","Y","N","N"),
group = c(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1))



Second: if you're working with data frames, it's worth learning dplyr. So install it, along with ggplot2, then load:


ggplot2


library(dplyr)
library(ggplot2)



Now we can count Y/N by group:


mydata %>%
count(group, drug)

# A tibble: 4 x 3
group drug n
<dbl> <fct> <int>
1 0 N 3
2 0 Y 5
3 1 N 5
4 1 Y 3



And plot counts versus group. We need to convert the groups to factors, since group is a categorical variable:


mydata %>%
count(group, drug) %>%
mutate(group = factor(group)) %>%
ggplot(aes(group, n)) +
geom_col(aes(fill = drug))



enter image description here





i appreciate for your point.
– Salman Lashkarara
Aug 30 at 5:21



Required, but never shown



Required, but never shown






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)