souravsarkar59
souravsarkar59

Reputation: 127

grouped barplot by another column

This may have been asked before, but couldn't find searching.

I'm trying to barplot of a variable called "pet" in my dataset called "habitat" which is categorical with 3 categories - "Y", "N", "Null".

The following code works:

>barplot(table(habitat$pet),main = "Pet Distribution", 
  xlab = "Pet categories", ylab = "count", col = c("darkblue"))

Now I have another binary column called "outcome". Is it easy to do a grouped barplot of frequencies by outcome?

I'm trying following, which isn't working:

>counts = table(habitat$pet[habitat$outcome == 0],habitat$pet[habitat$outcome == 1])
>barplot(counts,main = "Pet Distribution by Outcome", xlab = "Pet categories", 
    ylab = "count", col = c("darkblue","red"), beside = TRUE)

The error is in the " counts" part as the arguments don't have same length. Any other solution?

The data is like below:

ID   pet  outcome   
1     Y     1          
2     N     1
3     N     0
4     Y     0
...

Upvotes: 0

Views: 70

Answers (2)

Maurits Evers
Maurits Evers

Reputation: 50738

You can do something like this. I'm generating some sample data because your sample data don't seem to be representative (e.g. you've got no "NULL" entries).

# Generate sample data
set.seed(2017);
df <- data.frame(
    ID = 1:100,
    pet = sample(c("N", "Y", "NULL"), 100, prob = c(0.1, 0.8, 0.2), replace = T),
    outcome = sample(c(0, 1), 100, replace = T))

# Plot
ggplot(df, aes(pet)) + geom_bar()

enter image description here

Upvotes: 1

Vitor Bianchi Lanzetta
Vitor Bianchi Lanzetta

Reputation: 159

I am not sure that I got what you are looking for but try the following code:

if(!require(ggplot2)){install.packages('ggplot2')
library(ggplot2)
ggplot(data = habitat, aes(x = pet)) +
 geom_bar(position = 'fill', aes(fill = outcome)) +
 labs(x = 'Pet Categories', title = 'Pet Distribution by Outcome') +
 scale_fill_manual(values = c('darkblue','red'))

Skip position argument if you're not seeking for a proportional stacked barplot.

Upvotes: 0

Related Questions