darkage
darkage

Reputation: 857

Create Barplot in R

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:

enter image description here

My chart will have

  1. "Model Number" on the x-axis label instead of "Non Smoker" and "smoker"
  2. The bars will be the ranks (i.e., separate bars for rank 1,rank2 and rank 3)
  3. The y-axis will contain the frequency
  4. The legend will have the Rank category

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

Answers (2)

lukeA
lukeA

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))

enter image description here

Upvotes: 2

Rentrop
Rentrop

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 Barchart with ggplot

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

Related Questions