1 of 72

Module 4

Visualizing Nested Proportions

2 of 72

Syllabus 4th Module

3 of 72

Visualizing Nested Proportions

  • Scenarios where a dataset is broken into pieces defined by one categorical variable, such as political party, company, or health status. It is not uncommon, however, that we want to drill down further and break down a dataset by multiple categorical variables at once.
  • For example, in the case of parliamentary seats, we could be interested in the proportions of seats by party and by the gender of the representatives. Similarly, in the case of people’s health status, we could ask how health status further breaks down by marital status

4 of 72

Nested Proportions issues

​

  • nested proportions, because each additional categorical variable that we add creates a finer subdivision of the data nested within the previous proportions. There are several suitable approaches to visualize such nested proportions, including mosaic plots, treemaps, and parallel sets.
  • two flawed approaches to visualizing nested proportions. While these approaches may seem nonsensical to any experienced data scientist, Throughout this a dataset of 106 bridges in Pittsburg

5 of 72

Pie chart

6 of 72

explanation

  • However, this visualization is not valid. All the slices in a pie chart must add up to 100%, and here the slices add up to 135%. We reach a total percentage in excess of 100% because we are double-counting bridges.
  • Every bridge in the dataset is made of steel, iron, or wood, so these three slices of the pie already represent 100% of the bridges. Every crafts or modern bridge is also a steel, iron, or wood bridge, and hence is counted twice in the pie chart.

7 of 72

Side by side bar

  • A casual observer might conclude from Figure that there are five separate categories of bridges, and that, for example, modern bridges are neither made of steel nor of wood or iron

8 of 72

Mosaic plot

  • Whenever we have categories that overlap, it is best to show explicitly how they relate to each other. This can be done with a mosaic plot On first glance, a mosaic plot looks similar to a stacked bar plot However, unlike in a stacked bar plot, in a mosaic plot both the heights and the widths of individual sha ded areas vary.
  • Note that in we see two additional construction eras, emerging (from 1870 to 1889) and mature (1890 to 1939). In combination with crafts and modern, these construction eras cover all bridges in the dataset, as do the three building materials. This is a critical condition for a mosaic plot: every categorical variable shown must cover all the observations in the dataset

9 of 72

Mosaic plots

10 of 72

Process:

  • To draw a mosaic plot, we begin by placing one categorical variable along the x axis (here, era of bridge construction) and subdividing the x axis by the relative propor tions that make up the categories. We then place the other categorical variable along the y axis (here, building material) and, within each category along the x axis, subdi vide the y axis by the relative proportions that make up the categories of the y variable.
  • The result is a set of rectangles whose areas are proportional to the number of cases representing each possible combination of the two categorical variables.

11 of 72

treemaps

12 of 72

Treemaps

  • The bridges dataset can also be visualized in a related but distinct format called a tree map. In a treemap, just as is the case in a mosaic plot, we take an enclosing rectangle and subdivide it into smaller rectangles whose areas represent the proportions.
  • However, the method of placing the smaller rectangles into the larger one is different compared to the mosaic plot. In a treemap, we recursively nest rectangles inside each other. For example, in the case of the Pittsburgh bridges, we can first subdivide the total area into three parts representing the three building materials, wood, iron, and steel.
  • Then we can subdivide each of those areas further to represent the construction eras represented for each building material In principle we could keep going, nesting ever more smaller subdivisions inside each other, though relatively quickly the result would become unwieldy or confusing.

13 of 72

Tree map

  • States in the US visualized as a treemap. Each rectangle represents one state, and the area of each rectangle is proportional to the state’s land surface area. The states are grouped into four regions, West, Northeast, Midwest, and South.
  • The coloring is proportional to the number of inhabitants for each state, with darker colors represent ing larger numbers of inhabitants. Data source: 2010 US Decennial Census.

14 of 72

Nested Pies

  • The primary difference is the type of coordinate system: polar in the case of a pie chart versus Cartesian in the case of a mosaic plot or treemap. This close relationship between these different plots begs the question of whether some variant of a pie chart can be used to visualize this dataset.
  • There are two possibilities. First, we can draw a pie chart composed of an inner and an outer circle The inner circle shows the breakdown of the data by one variable (here, building material), and the outer circle shows the breakdown of each slice of the inner circle by the second variable (here, era of bridge construction). This visualization is reasonable, but I have my reservations, and therefore I have labeled it “ugly.”

15 of 72

Nested Pies

  • Breakdown of bridges in Pittsburgh by construction material (steel, wood, iron; inner circle) and by era of construction (crafts, emerging, mature, modern; outer circle). Numbers represent the counts of bridges within each category. Data source: Yoram Reich and Steven J. Fenves.

16 of 72

Better nested pie chart

  • Alternatively, we can first slice the pie into pieces representing the proportions according to one variable (e.g., material) and then subdivide these slices further according to the other variable (construction era)
  • In this way, in effect we are making a normal pie chart with a large number of small pie slices. However, we can then use coloring to indicate the nested nature of the pie.
  • Green colors represent wood bridges, orange colors represent iron bridges, and blue colors represent steel bridges. The darkness of each color represents the construction era, with darker colors corresponding to more recently constructed bridges.

17 of 72

  • Breakdown of bridges in Pittsburgh by construction material (steel, wood, iron) and by era of construction (crafts, emerging, mature, modern). Numbers represent the counts of bridges within each category. Data source: Yoram Reich and Steven J. Fenves.

18 of 72

Parallel sets

  • When we want to visualize proportions described by more than two categorical variables, mosaic plots, treemaps, and pie charts all can quickly become unwieldy.
  • A viable alternative in this case can be a parallel sets plot. In a parallel sets plot, we show how the total dataset breaks down by each individual categorical variable, and then we draw shaded bands that show how the subgroups relate to each other.
  • broken down the bridges dataset by construction material (iron, steel, wood), the length of each bridge (long, medium, short), the era during which each bridge was constructed (crafts, emerging, mature, modern), and the river each bridge spans (Allegheny, Monongahela, Ohio). The bands that connect the parallel sets are colored by construction material.

19 of 72

Parellel sets plots

  • Breakdown of bridges in Pittsburgh by construction material, length, era of construction, and the river they span, shown as a parallel sets plot. The coloring of the bands highlights the construction material of the different bridges.
  • This figure is visually busy, with many crisscrossing bands, but we do see that nearly any bridge of any type can be found to span each river.

20 of 72

Parallel sets

  • Breakdown of bridges in Pittsburgh by construction material, length, era of construction, and the river they span. This figure is similar to Figure 11-8, but now the coloring of the bands highlights the river spanned by the different bridges.
  • This figure is labeled “ugly” because the arrangement of the colored bands in the middle of the figure is very busy, and also because the bands need to be read from right to left. Data source: Yoram Reich and Steven J. Fenves

21 of 72

  • Breakdown of bridges in Pittsburgh by river, era of construction, length, and construction material. This figure differs from Figure 11-9 only in the order of the parallel sets. The modified order results in a figure that is easier to read and less busy. Data source: Yoram Reich and Steven J. Fenves.

22 of 72

Visualizing Associations Among Two or More Quantitative Variables

  • Many datasets contain two or more quantitative variables, and we may be interested in how these variables relate to each other. For example, we may have a dataset of quantitative measurements of different animals, such as the animals’ height, weight, length, and daily energy demands.
  • To plot the relationship of just two such variables, such as the height and weight, we will normally use a scatterplot. If we want to show more than two variables at once, we may opt for a bubble chart, a scatterplot matrix, or a correlogram. Finally, for very high-dimensional datasets, it may be useful to per form dimension reduction, for example in the form of principal components analysis.

23 of 72

Visualizing Associations Among Two or More Quantitative Variable

  • In this plot, head length is shown along the y axis and body mass along the x axis, and each bird is represented by one dot.
  • The dots form a dispersed cloud (hence the term scatterplot), yet undoubtedly there is a trend for birds with higher body mass to have longer heads.

24 of 72

Visualizing Associations among Male birds and female birds

  • The blue jay dataset contains both male and female birds, and we may want to know whether the overall relationship between head length and body mass holds up sepa rately for each sex. To address this question, we can color the points in the scatterplot by the gender of the bird
  • This figure reveals that the overall trend in head length and body mass is at least in part driven by the sex of the birds. At the same body mass, females tend to have shorter heads than males. At the same time, females tend to be lighter than males on average

25 of 72

  • Because the head length is defined as the distance from the tip of the bill to the back of the head, a larger head length could imply a longer bill, a larger skull, or both.
  • We can disentangle bill length and skull size by looking at another variable in the dataset, the skull size, which is similar to the head length but excludes the bill.
  • As we are already using the x position for body mass, the y position for head length, and the dot color for bird sex, we need another aesthetic to which we can map skull size.
  • One option is to use the size of the dots, resulting in a visualization called a bubble chart

26 of 72

  • the relationship between skull size and body mass is comparable for female and male birds, except that the female birds tend to be somewhat smaller.
  • However, the same is not true for the relationship between head length and body mass. There is a clear separation by sex. Male birds tend to have longer bills than female birds, all else being equal

27 of 72

Correlograms

  • When we have more than three to four quantitative variables, all-against-all scatter plot matrices quickly become unwieldy. In this case, it is more useful to quantify the amount of association between pairs of variables and visualize these quantities rather than the raw data.
  • One common way to do this is to calculate correlation coefficients. The correlation coefficient r is a number between –1 and 1 that measures to what extent two variables covary. A value of r = 0 means there is no association whatsoever, and a value of either 1 or –1 indicates a perfect association.

28 of 72

Correlograms

29 of 72

Correlations in mineral content

30 of 72

Magnitude of each correlation

31 of 72

Dimension Reduction

  • Dimension reduction relies on the key insight that most high-dimensional datasets consist of multiple correlated variables that convey overlapping information. Such datasets can be reduced to a smaller number of key dimensions without loss of much critical information.
  • As a simple, intuitive example, consider a dataset of multiple physical traits of people, including quantities such as each person’s height and weight, the lengths of their arms and legs, the circumferences of their waist, hips, and chest, etc. We can understand intuitively that all these quantities will relate first and fore most to the overall size of each person.

32 of 72

Example principal components analysis in 2 dimensions

33 of 72

34 of 72

Computation of individual glass fragments

35 of 72

36 of 72

Carbon dioxide emissions per persons

37 of 72

slopegraph

  • By contrast, if we have only a small number of observations and are primarily interested in the identity of each individual case, a slopegraph may be a bet ter choice. In a slopegraph, we draw individual measurements as dots arranged into two columns and indicate pairings by connecting the paired dots with a line. The slope of each line highlights the magnitude and direction of change. Figure 12-12 uses this approach to show the 10 countries with the largest difference in CO2 emis sions per person from 2000 to 2010.

38 of 72

slopegraph

39 of 72

Slopegraph 3 time points

  • For example, we can modify Figure 12-12 to show CO2 emissions at three time points, here the years 2000, 2005, and 2010 (Figure 12-13). This choice highlights countries with a large change in emissions over the entire decade as well as countries such as Qatar or Trinidad and Tobago for which there is a large difference in the trend seen for the first five-year interval and the second one

40 of 72

Visualizing Time Series and Other Functions of an Independent variable

  • As a first demonstration of a time series, we will consider the pattern of monthly preprint submissions in biology. Preprints are scientific articles that researchers post online before formal peer review and publication in a scientific journal.
  • The preprint server bioRxiv, which was founded in November 2013 specifically for researchers working in the biological sciences, has seen substantial growth in monthly submissions since. We can visualize this growth

41 of 72

Visualizing Time Series and Other Functions of an Independent variable

  • the dots are spaced evenly along the x axis, and there is a defined order among them. Each dot has exactly one left and one right neighbor (except the leftmost and rightmost points, which have only one neighbor each). We can visually emphasize this order by connecting neighboring points with lines (Figure 13-2). Such a plot is called a line graph.

42 of 72

Line graph

  • We can visually emphasize this order by connecting neighboring points with lines (Figure 13-2). Such a plot is called line graph.

43 of 72

Visualizing time series: Monthly submissions to preprint server

44 of 72

45 of 72

Multiple Time Series and Dose–Response Curves

  • For example, if we want to show the monthly submissions to multiple preprint servers, a scatterplot is not a good idea, because the individual time courses run into each other (Figure 13-5). Connecting the dots with lines alleviates this issue (Figure 13-6)

46 of 72

Multiple Time Series visualization

47 of 72

Monthly submissions to three preprint servers

48 of 72

49 of 72

50 of 72

Time Series of Two or More Response Variables

51 of 72

52 of 72

53 of 72

54 of 72

Visualizing trends

  • There are two fundamental approaches to determining a trend: we can either smooth the data by some method, such as a moving average, or we can fit a curve with a defined functional form and then draw the fitted curve.
  • Once we have identified a trend in a data set, it may also be useful to look specifically at deviations from the trend or to separate the data into multiple components, including the underlying trend
  • A trend is the general direction in which data moves over time. It may increase, decrease, or remain relatively stable

​

55 of 72

Example of a trend

  • consider the monthly sales of a shop.

​

​

  • Increasing trend
  • First, identify the general direction of the data by smoothing it or fitting a mathematical curve.
  • Then examine how the actual data differs from that trend and, if needed, separate long-term trends from seasonal patterns and irregular fluctuations.
  • This helps us understand the data more clearly and make better predictions.

​

Month

Sales (units)

January

100

February

120

March

110

April

140

May

150

June

145

56 of 72

Time series of the Dow Jones Industrial Average

  • Let us consider a time series of the Dow Jones Industrial Average (Dow Jones for short), a stock market index representing the price of 30 large, publicly owned US companies.
  • Specifically, we will look at the year 2009, right after the 2008 crash During the tail end of the crash, in the first 3 months of the year 2009, the market lost over 2,400 points (~27%). Then it slowly recovered for the remainder of the year.

57 of 72

Smoothing stock data

  • The act of smoothing produces a function that captures key patterns in the data while removing irrelevant minor detail or noise.
  • Financial analysts usually smooth stock market data by calculating moving averages.
  • To generate a moving average, we take a time window, say the first 20 days in the time series, calculate the average price over these 20 days, then move the time window by one day, so it now spans the 2nd to 21st days.
  • We then calculate the average over these 20 days, move the time window again, and so on. The result is a new time series consisting of a sequence of averaged prices.

58 of 72

Graph with Moving average:

59 of 72

Graph with Moving average:

60 of 72

LOESS curve:

  • One widely used method is locally estimated scatterplot smoothing (LOESS) [Cleveland 1979], which fits low-degree polynomials to subsets of the data. Importantly, the points in the center of each subset are weighted more heavily than points at the boundaries, and this weighting scheme yields a much smoother result than we get from a weighted average.
  • The LOESS curve shown in Figure 14-3 looks similar to the 100-day average in Figure 14-2, but this similarity should not be overinterpreted. The smoothness of a LOESS curve can be tuned by adjusting a parameter, and different parameter choices would have produced LOESS curves looking more like the 20-day or 50-day average.

61 of 72

LOESS smooth curve

62 of 72

A Spline

  • A spline is a piecewise polynomial function that is highly flexible yet always looks smooth. When working with splines, we will encounter the term knot. The knots in a spline are the endpoints of the individual spline segments. If we fit a spline with k segments, we need to spec if k + 1 knots.
  • While spline fitting is computationally efficient, in particular if the number of knots is not too large, splines have their own downsides.
  • Most importantly, there is a bewildering array of different types of splines, including cubic splines, B-splines, thin-plate splines, Gaussian process splines, and many others, and which one to pick may not be obvious. The specific choice of the type of spline and number of knots used can result in widely different smoothing functions for the same data

63 of 72

Different Smoothing display

64 of 72

How LOESS Works?

  • Local Subsets: Instead of fitting a single global model (like a straight line across all points), LOESS breaks the dataset into smaller local subsets (windows).
  • Low-Degree Polynomials: Within each subset, it fits a simple curve (typically linear or quadratic) using weighted least squares.
  • Distance-Based Weighting: Points near the center of the local window carry more weight than points near the boundaries.
  • This localized weighting ensures that distant outliers have minimal impact, producing a smoother trendline compared to basic moving or weighted averages. 2. Tunable Smoothness ParameterBandwidth / Span Parameter: The smoothness of a LOESS curve is controlled by a parameter (often denoted as $\alpha$ or span), which dictates the fraction of total data points used in each local subset.

65 of 72

Fuel tank data represented with analytical model

66 of 72

Head length versus body mass for 123 blue Jays

67 of 72

68 of 72

Monthly submission to preprint server BioRxiv

69 of 72

Freddie Mac House Price Index from 1980 through 2017

70 of 72

Detrended version of the Freddie Mac House price index

71 of 72

Keeling curve:

72 of 72

Time series decomposition of the keeling curve