Reputation: 857
I have a data of the following type:
Model No. Rank
1 1
2 2
1 1
3 1
1 2
2 2
3 2
1 3
2 1
2 2
3 3
3 3
Now I want to have a barplot similar to the following picture:
My chart will have
So, for Model1: the 1st bar will be for rank 1 and the corresponding value on y-axis will be 2, as there are two rank 1 entries for model 1. And similar concept for models 2 and 3.
How can this be achieved in R?
Upvotes: 0
Views: 773
Reputation: 54237
set.seed(1)
mat <- matrix(sample(5:50, 15),
ncol=3,
nrow=5,
dimnames=list(paste("Rank", 1:5),
paste("Model", 1:3)))
barplot(mat,beside=TRUE,col=2:6, ylim=c(0,100))
legend("topright", legend=rownames(mat), fill=2:6))
Upvotes: 2
Reputation: 21497
I would recoment using ggplot2
for a nice plot output
require(ggplot2)
# creating sample data set | making it factors is crucial
set.seed(1337)
model.no<-rep(1:4,each=5)
rank<-sample(1:3,20,TRUE)
dat<-data.frame(model.no=factor(model.no),rank=factor(rank))
# Plot
ggplot(data=dat, aes(model.no,fill=rank))+
geom_bar(position="dodge") + xlab("Your x-label")+ylab("Your y-label")
This gives you the following output
P.S.: If you dont want unused levels of rank to be droped, see 2 ways here: Don't drop zero count: dodged barplot
Upvotes: 3