📊 Histograms: Plotting Quantities

How many of this and that?

Quant Variables
Histograms
Mean
Author

Arvind V.

Published

November 15, 2022

Modified

June 27, 2024

Abstract
Quant and Qual Variable Graphs and their Siblings

Slides and Tutorials

R (Static Viz)   Radiant Tutorial  Datasets

Setting up R Packages

What graphs will we see today?

Variable #1 Variable #2 Chart Names Chart Shape
Quant None Histogram

What kind of Data Variables will we choose?

No Pronoun Answer Variable/Scale Example What Operations?
1 How Many / Much / Heavy? Few? Seldom? Often? When? Quantities, with Scale and a Zero Value.Differences and Ratios /Products are meaningful. Quantitative/Ratio Length,Height,Temperature in Kelvin,Activity,Dose Amount,Reaction Rate,Flow Rate,Concentration,Pulse,Survival Rate Correlation

Inspiration

Figure 1: Golf Drive Distance over the years

What do we see here? In about two-and-a-half decades, golf drive distances have increased, on the average, by 35 yards. The maximum distance has also gone up by 30 yards, and the minimum is now at 250 yards, which was close to average in 1983! What was a decent average in 1983 is just the bare minimum in 2017!!

Is it the dimples that the golf balls have? But these have been around a long time…or is it the clubs, and the swing technique invented by more recent players?

Now, let us listen to the late great Hans Rosling from the Gapminder Project, which aims at telling stories of the world with data, to remove systemic biases about poverty, income and gender related issues.

How do Histograms Work?

Histograms are best to show the distribution of raw Quantitative data, by displaying the number of values that fall within defined ranges, often called buckets or bins. We use a Quant variable on the x-axis and the histogram shows us how frequently different values occur for that variable by showing counts/frequencies on the y-axis. The x-axis is typically broken up into “buckets” or ranges for the x-variable, And usually you can adjust the bucket ranges to explore frequency patterns. For example, you can shift histogram buckets from 0-1, 1-2, 2-3, etc. to 0-2, 2-4, etc. Histograms do not usually show spaces between buckets because the buckets represent contiguous ranges, while bar charts show spaces to separate each (unconnected) category/level within a Qual variable.

Although Bar Charts may look similar to Histograms, the two are different. Bar Charts show counts of observations with respect to a Qualitative variable. For instance, bar charts show categorical data with multiple levels, such as fruits, clothing, household products in an inventory. Each bar has a height proportional to the count per shirt-size, in this example.

Case Study-1: diamonds dataset

We will first look at at a dataset that is directly available in R, the diamonds dataset.

Examine the Data

As per our Workflow, we will look at the data using all the three methods we have seen.

Business Insights on Examining the diamonds dataset
  • This is a large dataset (54K rows).
  • There are several Qualitative variables: cut, color and clarity. These have 5, 7, and 8 levels respectively. The fact that the class for these is ordered suggests that these are factors and that the levels have a sequence/order.
  • carat, price, x, y, z, depth and table are Quantitative variables.
  • There are no missing values for any variable, all are complete with 54K entries.
Hypothesis and Research Questions
  • The target variable for an experiment that resulted in this data might be the price variable. Which is a numerical Quant variable.
  • There are also predictor variables such as carat (Quant), color(Qual), cut(Qual), and clarity(Qual).
  • Other predictor variables might be x, y, depth, table(all Quant)
  • Research Questions:
    • What is the distribution of the target variable price?
    • What is the distribution of the predictor variable carat?
    • Does a price distribution vary based upon type of cut, clarity, and color?

These should do for now. Try and think of more Questions!

Plotting Histograms

Let’s plot some histograms to answer each of the Hypothesis questions above.

Question-1: What is the distribution of the target variable price?

Question-1: What is the distribution of the target variable price?

Business Insights-1

  • The price distribution is heavily skewed to the right.
  • There are a great many diamonds at relativly low prices, but there are a good few diamonds at very high prices too.
  • Using a high number of bins does not materially change the view of the histogram.

Question-2: What is the distribution of the predictor variable carat?

Question-1: Question-2: What is the distribution of the predictor variable carat?

Business Insights-2

  • carat also has a heavily right-skewed distribution.
  • However, there is a marked “discreteness” to the distribution. Some values of carat are far more common than others. For example, 1, 1.5, and 2 carat diamonds are large in number.
  • Why does the X-axis extend up to 5 carats? There must be some, very few, diamonds of very high carat value!

Question-3: Does a price distribution vary based upon type of cut, clarity, and color?

Does a price distribution vary based upon type of cut, clarity, and color?

Business Insights-3

  • The price distribution is heavily skewed to the right AND This long-tailed nature of the histogram holds true regardless of the cut of the diamond.
  • See the x-axis range for each plot in Plot D! Price ranges are the same regardless of cut !! Very surprising! So cut is perhaps not the only thing that determines price…
  • Facetting the plot into small multiples helps look at patterns better: overlapping histograms are hard to decipher. Adding color defines the bars in the histogram very well.
A Hypothesis

The surprise insight above should lead you to make a Hypothesis! You should decide whether you want to investigate this question further, making more graphs, as we will see. Here, we are making a Hypothesis that more than just cut determines the price of a diamond.

An Interactive App for Histograms

Type in your Console:

```{r}
#| eval: false
install.packages("shiny")
library(shiny)
runExample("01_hello")      # an interactive histogram
```

Case Study-2: race dataset

Import data

The data come from the TidyTuesday, project, a weekly social learning project dedicated to gaining practical experience with R and data science. In this case the TidyTuesday data are based on International Trail Running Association (ITRA) data but inspired by Benjamin Nowak. We will use the TidyTuesday data that are on GitHub. Nowak’s data are also available on GitHub.

Examine the race Data

Let us look at the dataset using all our three methods:

Business Insights from race data
  • We have two datasets, one for races (race_df) and one for the ranking of athletes (rank_df).
  • There is atleast one common column between the two, the race_year_id variable.
  • Overall, there are Qualitative variables such as country, city,gender, and participation. This last variables seems badly coded, with entries showing solo and Solo.
  • Quantitative variables are rank, time,time_in_seconds, age from rank_df; and distance, elevation_gain, elevation_loss,particants, and aid_stations from race_df.
  • We have 1207 races and over 130K participants! But some races do show zero participants!! Is that an error in data entry?

EDA with race datasets

Question #1

Which countries host the maximum number of races? Which countries send the maximum number of participants??

The top three locations for races were the USA, UK, and France. These are also the countries that send the maximum number of participants, naturally!

Question #2

Which countries have the maximum number of winners (top 3 ranks)?

1240 Participants from the USA have been top 3 finishers. Across all races…

Question #3

Which countries have had the most top-3 finishes in the longest distance race?

Here we see we have ranks in one dataset, and race details in another! How do we do this now? We have to join the two data frames into one data frame, using a common variable that uniquely identifies observations in both datasets.

Wow….France has one the top 10 positions 26 times in the longest races… which take place in France, Thailand, Chad, Australia, and Portugal. So although the USA has the greatest number of top 10 finishes, when it comes to the longest races, it is 🇫🇷 vive la France!

Question #4

What is the distribution of the finishing times, across all races and all ranks?

So the distribution is (very) roughly bell-shaped, spread over a 2X range. And some people may have dropped out of the race very early and hence we have a small bump close to zero time! The histogram shows three bumps…at least one reason is that the distances to be covered are not the same…but could there be other reasons? Like altitude_gained for example?

Question #5

What is the distribution of race distances?

Curious…some of these zero-distance races have had participants too! Perhaps these were cancelled events…all of them are stated to be 100 mile events…

Question #6

For all races that have a distance around 150, what is the distribution of finishing times? Can these be split/facetted using start_time of the race (i.e. morning / evening) ?

We see that finish times tend to be longer for afternoon and evening start races; these are lower for early morning and night time starts. Mid-day starts show a curious double hump in finish times that should be studied.

Distributions and Densities in the Wild

Before we conclude, let us look at a real world dataset: populations of countries. This dataset was taken from Kaggle https://www.kaggle.com/datasets/ulrikthygepedersen/populations. Click on the icon below to save the file into a subfolder called data in your project folder:

pop <- read_csv("data/populations.csv")
pop
inspect(pop)

categorical variables:  
          name     class levels     n missing
1 country_code character    265 16400       0
2 country_name character    265 16400       0
                                   distribution
1 ABW (0.4%), AFE (0.4%), AFG (0.4%) ...       
2 Afghanistan (0.4%) ...                       

quantitative variables:  
   name   class  min       Q1  median       Q3        max         mean
1  year numeric 1960   1975.0    1991     2006       2021 1.990529e+03
2 value numeric 2646 986302.5 6731400 46024452 7888408686 2.140804e+08
            sd     n missing
1 1.789551e+01 16400       0
2 7.040554e+08 16400       0

Let us plot densities/histograms for value:

## Set graph theme
theme_set(new = theme_custom())
##

##
gf_histogram(~ value, data = pop, title = "Long Tailed Histogram") 
##
gf_density(~ value, data = pop, title = "Long Tailed Density")

These graphs convey very little to us: the data is very heavily skewed to the right and much of the chart is empty. There are many countries with small populations and a few countries with very large populations. Such distributions are also called “long tailed” distributions. To develop better insights with this data, we should transform the variable concerned, using say a “log” transformation:

## Set graph theme
theme_set(new = theme_custom())
##

gf_histogram(~ log10(value), data = pop, title = "Histogram with Log transformed x-variable") 
##
gf_density(~ log10(value), data = pop, title = "Density with Log transformed x-variable")

Be prepared to transform your data with log or sqrt transformations when you see skewed distributions! Salaries, Instagram connections, number of customers vs Companies, net worth / valuation of Companies, extreme events on stock markets….all of these could have highly skewed distributions. In such a case, the standard statistics of mean/median/sd may not convey too much information.

Several distribution shapes exist, here is an illustration of the 6 most common ones:

Type_of_Distributions

Type_of_Distributions

What insights could you develop based on these distribution shapes?

  • Bimodal: Maybe two different systems or phenomena or regimes under which the data unfolds. Like our geyser above. Or a machine that works differently when cold and when hot. Intermittent faulty behaviour…
  • Comb: Some specific Observations occur predominantly, in an otherwise even spread or observations. In a survey many respondents round off numbers to nearest 100 or 1000. Check the distribution of the diamonds dataset for carat values which are suspiciously integer numbers in too many cases.
  • Edge Peak: Could even be a data entry artifact!! All unknown / unrecorded observations are recorded as \(999\) !!🙀
  • Normal: Just what it says! Course Marks in a Univ cohort…
  • Skewed: Income, or friends count in a set of people. Do UI/UX peasants have more followers on Insta than say CAP people?
  • Uniform: The World is not flat. Anything can happen within a range. But not much happens outside! Sharp limits…

Z-scores

Often when we compute wish to compare distributions with different values for means and standard deviations, we resort to a scaling of the variables that are plotted in the respective distributions.

Although the densities all look the same, they are are quite different! The x-axis in each case has two scales: one is the actual value of the x-variable, and the other is the z-score which is calculated as:

\[ z_x = \frac{x - \mu_{x}}{\sigma_x} \]

With similar distributions (i.e. normal distributions), we see that the variation in density is the same at the same values of z-score for each variable. However since the \(\mu_i\) and \(\sigma_i\) are different, the absolute value of the z-score is different for each variable. In the first plot (from the top left), \(z = 1\) corresponds to an absolute change of \(5\) units; it is \(15\) units in the plot directly below it.

Our comparisons are done easily when we compare differences in probabilities at identical z-scores, or differences in z-scores at identical probabilities.

Conclusion

To complicate matters: Having said all that, the histogram is really a bar chart in disguise! You probably suspect that the “bucketing” of the Quant variable is tantamount to creating a Qual variable! Each bucket is a level in this fictitious bucketed Quant variable.

  • Histograms, Frequency Distributions, and Box Plots are used for Quantitative data variables
  • Histograms “dwell upon” counts, ranges, means and standard deviations
  • We can split histograms on the basis of another Qualitative variable.
  • Long tailed distributions need care in visualization and in inference making!

Your Turn

Datasets

  1. Click on the Dataset Icon above, and unzip that archive. Try to make distribution plots with each of the three tools.
  2. A dataset from calmcode.io https://calmcode.io/datasets.html
  3. Old Faithful Data in R (Find it!)

inspect the dataset in each case and develop a set of Questions, that can be answered by appropriate stat measures, or by using a chart to show the distribution.

References

  1. See the scrolly animation for a histogram at this website: Exploring Histograms, an essay by Aran Lunzer and Amelia McNamara https://tinlizzie.org/histograms/?s=09
  2. Minimal R using mosaic.https://cran.r-project.org/web/packages/mosaic/vignettes/MinimalRgg.pdf
  3. Sebastian Sauer, Plotting multiple plots using purrr::map and ggplot
R Package Citations
Package Version Citation
ggridges 0.5.6 Wilke (2024)
NHANES 2.1.0 Pruim (2015)
TeachHist 0.2.1 Lange (2023)
TeachingDemos 2.13 Snow (2024)
visualize 4.5.0 Balamuta (2023)
Balamuta, James. 2023. visualize: Graph Probability Distributions with User Supplied Parameters and Statistics. https://CRAN.R-project.org/package=visualize.
Lange, Carsten. 2023. TeachHist: A Collection of Amended Histograms Designed for Teaching Statistics. https://CRAN.R-project.org/package=TeachHist.
Pruim, Randall. 2015. NHANES: Data from the US National Health and Nutrition Examination Study. https://CRAN.R-project.org/package=NHANES.
Snow, Greg. 2024. TeachingDemos: Demonstrations for Teaching and Learning. https://CRAN.R-project.org/package=TeachingDemos.
Wilke, Claus O. 2024. ggridges: Ridgeline Plots in ggplot2. https://CRAN.R-project.org/package=ggridges.
Back to top

Citation

BibTeX citation:
@online{v.2022,
  author = {V., Arvind},
  title = {📊 {Histograms:} {Plotting} {Quantities}},
  date = {2022-11-15},
  url = {https://av-quarto.netlify.app/content/courses/Analytics/Descriptive/Modules/22-Histograms/},
  langid = {en},
  abstract = {Quant and Qual Variable Graphs and their Siblings}
}
For attribution, please cite this work as:
V., Arvind. 2022. “📊 Histograms: Plotting Quantities.” November 15, 2022. https://av-quarto.netlify.app/content/courses/Analytics/Descriptive/Modules/22-Histograms/.