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!
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))
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.
What's
my_matches
? It's not defined anywhere.– neilfws
Aug 30 at 5:02