Plot two barplot in R

Viewed 78
 data <- as.matrix(data.frame("A" = c(18,7),
                                "B+" = c(3,2),
                                "B" = c(3,3),
                                "C+" = c(6,0),
                                "C" = c(7,0),
                                "D" = c(0,4),
                                "E" = c(5,23)))
    
    
    barplot (data,
            col = c("red","blue"),
            beside = TRUE,
            xlab = "Grade",
            ylab = "Frequency")
    
    
    legend("topleft",
           c("IFC6503-A","IFC6510"),
           fill = c("red","blue"),
           inset = c(.01,0)
    )

I plot two barplot together, the barplot it contain grade, from two different data, the grade is by A B+ B C+ C D E , but the result B+ and C+ is not appear, just appear B. and C. , is my code is wrong or can you guys correct my code?

3 Answers

Do not use special character + in colnames as already pointed by Bernhard: Here is a way where you could relabel the x axis of the plot by hand:

  1. Give adequate colnames in your matrix: see here comment of whuber: https://stats.stackexchange.com/questions/163280/naming-convention-for-column-names

  2. use xaxt = "n" in barplot to remove x labels

  3. use axis to insert x labels manually:

data <- as.matrix(data.frame("A" = c(18,7),
                             "Bplus" = c(3,2),
                             "B" = c(3,3),
                             "Cplus" = c(6,0),
                             "C" = c(7,0),
                             "D" = c(0,4),
                             "E" = c(5,23)))


barplot (data,
         col = c("red","blue"),
         beside = TRUE,
         xlab = "Grade",
         ylab = "Frequency",
         xaxt = "n")
         
axis(1, at = seq(2, 20, 3), labels = c("A", "B+", "B", "C+", "C", "D", "E"))


legend("topleft",
       c("IFC6503-A","IFC6510"),
       fill = c("red","blue"),
       inset = c(.01,0)
)

enter image description here

The name of the columns in the data doesn't have B+ and C+

You can just rename the columns like this after loading the file:

colnames(data)[2] <-'B+'
colnames(data)[4] <-'C+'

Now plot with the same code

barplot (data,
         col = c("red","blue"),
         beside = TRUE,
         xlab = "Grade",
         ylab = "Frequency")


legend("topleft",
       c("IFC6503-A","IFC6510"),
       fill = c("red","blue"),
       inset = c(.01,0)
)

Output

A tidyverse approach

library(tidyverse)

data %>% 
  pivot_longer(cols = everything()) %>% 
  group_by(name) %>% 
  mutate(
    name = str_replace(name,"\\.","+"),
    grp = row_number(),
    grp = if_else(grp == 1,"IFC6503-A","IFC6510")
    ) %>% 
  ggplot(aes(x = name, y = value,fill = grp))+
  geom_col(position = position_dodge())+
  scale_fill_manual(values = c("IFC6503-A" = "red","IFC6510" = "blue"))+
  labs(
    x = "Grade",
    y = "Frequency"
  )

enter image description here

Related