Skip to main content

Section 3.2 Geom_Histogram()

Finally, we can create a graph to see the distribution of crime rates across Pennsylvania cities. Specifically, we can create a histogram that is useful for displaying the distribution of continuous data by dividing it into bins (i.e., bar charts are useful for visualizing the frequency of each category in categorical variables). We are going to use ggplot2 to accomplish this task.
crime.rate.table <- X2018.UCR.PA.cleaned %>%
  ggplot(aes(x = crime.rate, fill = after_stat(count))) +
  geom_histogram() +
  labs(x = "Crime rates", y = "Frequency", title = "Distribution of Crime Rates") +
  theme_minimal()
crime.rate.table
X2018.UCR.PA.cleaned is the data frame containing the variable I wanted to visualize, and aes(x = crime.rate) specifies the crime.rate variable that I wanted to plot on the x-axis. geom_histogram() was the function used to create the histogram. fill = after_stat(count) within the aes() function assigned a fill color to the bars based on the count of observations in each bin. This results in a gradient color scale where darker colors represent higher frequencies.
In this chapter, we reviewed how to create a variable and produce summary statistics using the concept of crime rates. In the next chapter, we will learn more about central tendency and spread, which are critical statistical measures that visualize data patterns.