Barplot form data in a dataframe

Viewed 43

I have the following data in a data frame;

TYPE_OF_COMPANY    COUNT_OF_COMPANIES
    
AIM-Listed                  876
Charitable-organisation          82
Industrial-Provident             50
Limited-Partnership               2
Limited by Guarantee            277
Limited Liability Partnership   167
Listed-LSE                     1131
Not-Companies-Act                75
Private Limited Company        1163
Public-Unlisted                 418
Royal-Charter                     5
Unlimited                       111

I want represent this data is a bar plot. When this data is in a table then my code succeeds but I was having a problem sorting the data but I was happy with the out put using the following code:

barplot(counts,  
        Xlab='TYPES_OF_COMPANIES', ylab='TYPE_OF_COMPANY', ylim=c(0,1200),
        names.arg = c("LP", "RC", "IP", 
          "N-C-A", "C-O", "Guarantee", 
              "U-L", "C-O",
              "LLP","L-G","P-U",
               "A-L", "LSE", "PL"),
        main='Number of Different Types of Companies in the database')

When I tried to modify the code to use a data frame, it gave me an error. I know I could use ggplot2 package to do it, but this is for illustration, and I want to do it in base R.

You can show me how to sort the table or how to make barplot work with the data frame.

Any help is greatly appreciated.

2 Answers

Does this work for you?

barplot(sort(counts$COUNT_OF_COMPANIES),  
        xlab = 'TYPES_OF_COMPANIES', ylab = 'Count', ylim = c(0, 1200),
        names.arg =  c("AIM", "Charity", "I-P", "L-P", 
                    "L-G", "LLP", "L-LSE", "NCA", 
                    "PLC", "P-UL", "RC", "UL")[order(counts$COUNT_OF_COMPANIES)],
        main = 'Number of Different Types of Companies in the database')

enter image description here

Instead of writing the names.arg, You could do:

labs <- c("AIM", "Charity", "I-P", "L-P", "L-G", "LLP",  
            "L-LSE", "NCA", "PLC", "P-UL", "RC", "UL")

new_df <- transform(df, labels = ordered(labs, labs[order(COUNT_OF_COMPANIES)]))

barplot(COUNT_OF_COMPANIES~labels, new_df,  xlab='TYPES_OF_COMPANIES', 
        ylab='TYPE_OF_COMPANY', 
        main='Number of Different Types of Companies in the database')

enter image description here

Related