Bar Graphs in ggplot2

Author

Mohammed Al haqbani

Introduction

in this exercise, I will show you how to create a bar graph in ggplot2. The bar graph is a type of chart that represents data in the form of rectangular bars. The length of the bar is proportional to the value it represents. Bar graphs are used to compare different categories of data and show the relationship between them. In this project, I will use the diamonds data set from the ggplot2 package to create a bar graph that shows the proportion of diamonds in each category of the cut variable.

Data used

The data used in this project is the diamonds data set from the ggplot2 package. The data set contains 53940 rows and 10 columns.

Required libraries

  • ggplot2

  • dplyr

  • formats

Follow along .. 👍

library(ggplot2)
library(dplyr)
library(forcats)

diamonds <- diamonds

diamonds %>%
    summarize(prop = n() / nrow(diamonds), .by = cut) %>%
    mutate(cut = forcats::fct_reorder(cut, prop)) %>%
    ggplot(aes(prop, cut)) +
    geom_col(aes(fill = as.numeric(cut) == 5)) +
    theme_minimal() +
    theme(
        panel.grid.minor = element_blank(),
        panel.grid.major = element_blank(),
        axis.line.x = element_line(color = "grey80", linewidth = .4),
        axis.ticks.x = element_line(color = "grey80", linewidth = .4),
        axis.title.y = element_blank(),
        plot.margin = margin(10, 15, 10, 15))+
    facet_wrap(~ cut,ncol = 1, scales = "free_y") +
    scale_x_continuous(
        name = "Proporation", expand = c(0, 0), limits = c(0, .4),
        labels = scales::label_percent())+
    scale_y_discrete(guide = "none", expand = expansion(add = c(.8,.6))) +
    scale_fill_manual(values = c("grey50", "#1D787A"), guide = "none") +
    theme(strip.text = element_text(
        hjust = 0, margin = margin(1, 0, 1, 0), 
        size = rel(1.1), face = "bold"))+
    geom_text(
    aes(label = paste0("  ", sprintf("%2.1f", prop * 100), "%  "), 
        color = prop > .05, hjust = prop > .05),
    size = 4, fontface = "bold", family = "Spline Sans"
  ) + scale_color_manual(values = c("black", "white"), guide = "none")

Made with ❤️ by Mohammed Al haqbani

Linkedin Page: 🔗 https://www.linkedin.com/in/alhagbani/