Search code examples
rdataframeggplot2geom-bar

How to Create comparison bar graph


I have below mentioned datafram:

Month    Fig1    Fig2
Mar-17   10      12
Feb-17   25      18
Jan-17   10      15
Dec-16   11      18
Nov-16   10      15

I want to create a colorful bar graph for this, i have tried below mentioned code but it didn't work.

bargraph <- ggplot(data = df1) +
  geom_bar(aes(x = Month,
                y = value,
                group = variable,
                color = variable)) +
  theme(legend.title=element_blank())

and further i want to store that graph in JPG or PNG to send it through mailR.


Solution

  • I have modified your code as below.

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    df2 <- df1 %>% 
      gather(Fig, Value, -Month) %>%
      mutate(Month = factor(Month, 
                            levels = c("Nov-16", "Dec-16", "Jan-17", "Feb-17", "Mar-17"))) %>%
      arrange(Month)
    
    bargraph <- ggplot(data = df2) +
      geom_bar(aes(x = Month,
                   y = Value,
                   fill = Fig,
                   color = Fig),
               stat = "identity",
               position = position_dodge()) +
      theme(legend.title=element_blank())
    bargraph
    

    enter image description here

    To use ggplot2 to plot a group bar chart, we need to convert df1 from wide-format to long-format, as df2. And then, it is necessary to reorder the Month column because that determines the order on the x-axis. Therefore, I converted the Month column to factor and use arrange to reorder it.

    In geom_bar, we need to specify stat = "identity" and position = position_dodge(). It is possible to use geom_col to create the same plot without stat = "identity".

    To save the plot, we can use the ggsave function. You can specify the file directory in the filename argument.

    ggsave(filename = "bargraph.jpg", plot = bargraph)
    

    Finally, using is really a completely different question. Please search for related questions on Stack Overflow. If you could not find the information you need, then you can consider to ask a new question.

    DATA

    df1 <- read.table(text = "Month    Fig1    Fig2
    'Mar-17'   10      12
                      'Feb-17'   25      18
                      'Jan-17'   10      15
                      'Dec-16'   11      18
                      'Nov-16'   10      15",
                      header = TRUE, stringsAsFactors = FALSE)