class: center, middle, title-slide .title[ # Perception and Visualization ] .author[ ### Luke Tierney ] .institute[ ### University of Iowa ] .date[ ### 2023-05-06 ] --- <link rel="stylesheet" href="stat4580.css" type="text/css" /> ## Some River Flow Data ```r river <- scan("https://www.stat.uiowa.edu/~luke/data/river.dat") plot(river) ``` <img src="percep_files/figure-html/unnamed-chunk-1-1.png" style="display: block; margin: auto;" /> --- layout: true ## A Simple Model of Visual Perception --- The eyes acquire an image, which is processed through three stages of memory: -- * Iconic memory -- * Working memory, or short-term memory -- * Long-term memory --- ### Iconic Memory The first processing stage of an image happens in iconic memory. -- * Images remain in iconic memory for less than a second. -- * Processing in iconic memory is massively parallel and automatic. -- * This is called _preattentive processing_. -- Preattentive processing is a fast recognition process. --- ### Working Memory Meaningful visual chunks are moved from iconic memory to short term memory. -- These chunks are used by conscious, or attentive, processing. -- Attentive processing often involves conscious comparisons or search. -- Short term memory is limited; -- * information is retained for only a few seconds; -- * only three or fours chunks can be held at a time. -- Chunks can be of varying size; a coherent pattern can form a single chunk even if it is quite large. -- If more chunks are needed or chunks are needed longer they need to be reacquired or retrieved from long term memory. --- ### Long Term Memory Long term visual memory is built up over a lifetime, though infrequently used visual chunks may become lost. -- Chunks processed repeatedly in working memory may be transferred to long term memory. -- Common patterns and contextual information can be retrieved from long term memory for attentive processing in working memory. --- ### Visual Design Implications Try to make as much use of preattentive features as possible. -- Recognize when preattentive features might mislead. -- For features that require attentive processing keep in mind that working memory is limited. --- layout: true ## Some Examples of Challenges --- ### Context Matters Which of the inner circles is larger, or are they the same size? <!-- http://junkcharts.typepad.com/junk_charts/2012/09/insufficiency-and-illusions.html --> .pull-left[ <img src="percep_files/figure-html/unnamed-chunk-2-1.png" style="display: block; margin: auto;" /> ] -- .pull-right[ <img src="percep_files/figure-html/unnamed-chunk-3-1.png" style="display: block; margin: auto;" /> ] --- Which of the lines is longer, or are they the same length? .pull-left[ <img src="percep_files/figure-html/unnamed-chunk-4-1.png" style="display: block; margin: auto;" /> ] -- .pull-left[ <img src="percep_files/figure-html/unnamed-chunk-5-1.png" style="display: block; margin: auto;" /> ] --- The sine Illusion: which of the bars are longer, or are they the same length? .hide-code[ ```r x <- seq(0, 5 * pi, length.out = 100) w <- 0.5 plot(x, sin(x), ylim = c(-1, 1 + w), type = "n") segments(x0 = x, y0 = sin(x), y1 = sin(x) + w, lwd = 3) ``` <img src="percep_files/figure-html/unnamed-chunk-6-1.png" style="display: block; margin: auto;" /> ] <!-- http://vanseodesign.com/web-design/color-luminance/--> --- Which of the squares A and B is darker, or are they the same shade? .pull-left[ <img src="../img/chess1.png" width="440" style="display: block; margin: auto;" /> ] -- .pull-right[ <img src="../img/chess2.png" width="440" style="display: block; margin: auto;" /> ] --- name: some-optical-illusions ### Some Optical Illusions [R implementations](http://rpubs.com/kohske/R-de-illusion) of some optical illusions by Kohske Takahashi: <!-- Some also used in https://cran.r-project.org/web/packages/knitrBootstrap/vignettes/illusions.html First saw these in http://blog.revolutionanalytics.com/2012/12/create-optical-illusions-with-r.html --> Are these lines parallel? <img src="percep_files/figure-html/unnamed-chunk-9-1.png" style="display: block; margin: auto;" /> --- Again, are these lines parallel? <img src="percep_files/figure-html/unnamed-chunk-10-1.png" style="display: block; margin: auto;" /> --- [Scintillating grid illusion](https://psychology.fandom.com/wiki/Grid_illusion#Scintillating_grid_illusion): Black dots at the intersections appear and disappear; are they real? <!-- the circles need to be a little bigger than the lines --> <img src="percep_files/figure-html/unnamed-chunk-11-1.png" style="display: block; margin: auto;" /> --- [Hermann grid illusion](https://psychology.fandom.com/wiki/Grid_illusion#Hermann_grid_illusion): "Ghost-like" grey blobs at the intersections of white lines. <img src="percep_files/figure-html/unnamed-chunk-12-1.png" style="display: block; margin: auto;" /> --- Grid illusion in a cartogram: <!-- ## nolint start: line_length --> <!-- https://twitter.com/hrbrmstr/status/1281681469476413447 --> <img src="percep_files/figure-html/unnamed-chunk-13-1.png" width="60%" style="display: block; margin: auto;" /> <!-- ## nolint end --> --- A case where there are more dots than we can see at once: <!--https://twitter.com/teslaphx/status/1373436726727745537?s=11 --> <img src="../img/disappearing-dots.jpeg" width="40%" style="display: block; margin: auto;" /> --- Red from black and white: <!-- https://twitter.com/AkiyoshiKitaoka/status/1591784897282478080 --> <img src="../img/red_from_black_and_white.jpeg" width="50%" style="display: block; margin: auto;" /> --- Some illusions in pictures: .pull-left[ <!-- https://twitter.com/nxthompson/status/1357147968328118272?s=11 --> <div class="figure" style="text-align: center"> <img src="../img/man_in_snow.jpeg" alt="A man running into the snow" width="50%" /> <p class="caption">A man running into the snow</p> </div> ] -- .pull-right[ <!-- https://twitter.com/markysumm/status/1337725851799056386?s=11 --> <div class="figure" style="text-align: center"> <img src="../img/cookie-monster.jpeg" alt="Once you see Cookie Monster, you can’t unsee it" width="50%" /> <p class="caption">Once you see Cookie Monster, you can’t unsee it</p> </div> ] -- A large collection of optical illusions is available at <https://michaelbach.de/ot/index.html>. -- Other links to optical illusions can be found [here](https://onlinemasters.ohio.edu/masters-health-administration/health-brain-games-optical-illusions/). --- ### Motion .hide-code[ ```r n <- 50 x <- 2 * (1 : n) y <- rep(2, n) lim <- c(min(x) + 0.1 * (max(x) - min(x)), max(x) - 0.1 * (max(x) - min(x))) v <- TRUE for (i in 1 : 2) { plot(x + v, y, xlim = lim) v <- ! v Sys.sleep(0.1) } ``` <img src="percep_files/figure-html/chunk-label.gif" style="display: block; margin: auto;" /> ] <!-- More motion illusions: https://twitter.com/AnneLaure_David/status/1513597990669271045 https://twitter.com/jagarikin/status/1531115731223339008 --> --- .pull-left[ <img src="../img/3dscatter_percep.gif" width="75%" style="display: block; margin: auto;" /> {{content}} ] -- Images contain no information about the direction of the rotation. {{content}} -- Your mind picks a direction. -- .pull-right[ .hide-code[ ```r library(rgl) d <- data.frame(x = rnorm(1000), y = rnorm(1000), z = rnorm(1000)) points3d(d) par3d(FOV = 1) ## removes perspective distortion if (interactive()) play3d(spin3d(axis = c(0, 0, 1), rpm = 30), duration = 20) ```
] {{content}} ] -- Interactive rotation can help. {{content}} -- Depth cueing and perspective can also help. --- ### Popout and Distractors Where is the red dot: <img src="percep_files/figure-html/unnamed-chunk-23-1.png" style="display: block; margin: auto;" /> --- <img src="percep_files/figure-html/unnamed-chunk-24-1.png" style="display: block; margin: auto;" /> --- <img src="percep_files/figure-html/unnamed-chunk-25-1.png" style="display: block; margin: auto;" /> --- layout: true ## Items, Attributes, Marks, and Channels --- To evaluate or design a visualization it is useful to have some terms for the components. -- Several schools have developed different but similar sets of terms. -- Some References: * Bertin, J. (1967), _The Semiology of Graphics_. * Cleveland, W. S. (1988), _The Elements of Graphing Data_. * Cleveland, W. S. (1993), _Visualizing Data_. * Few, S. (2012), _Show Me the Numbers: Designing Tables and Graphs to Enlighten_, 2nd ed. * Munzner, T. (2014), _Visualization Analysis and Design_ * Ware, C. (2012), _Information Visualization: Perception for Design_, 3rd ed. * Wilkinson, L. (2005), _The Grammar of Graphics_, 2nd ed. --- Munzner uses the terminology of items, attributes, links, marks, and channels: -- * _Items_ are the basic units on which data is collected: the entities represented by the rows in a _tidy_ data frame. -- * _Attributes_ are the numerical or categorical features of the data items we want to represent; the variables in a tidy data frame. -- * _Links_ are relations among items: e.g. months within a year, or countries within a continent. -- * _Marks_ are the geometric entities used to represent items: points, lines, areas. These correspond to the simple `geom` objects in `ggplot`. -- * _Visual channels_ are features of marks that can be used to reflect values of attributes. --- Channels correspond approximately to aesthetics in `ggplot` but are more focused on the visual aspect: -- * An `x` aesthetic that is transformed to polar coordinates is a different channel than an `x` aesthetic representing a position on a standard linear scale. -- Channels are used to _encode_ attributes (_aesthetic mappings_). -- A single attribute can be encoded in several channels. -- * This makes the attribute easier to perceive. -- * But is also uses up available channels. -- Some channels are well suited to encode quantitative or ordered values; they are _quantitatively perceived_. -- Others are only suited for nominal values. --- A useful classification, adapted from Few(2012): | Type | Channel | Quantitatively Perceived? | |:---------|:------------|:--------------------------- | | Form | Length | Yes | | | Width | Yes, but limited | | | Orientation | No | | | Size | Yes, but limited | | | Shape | No | | Color | Hue | No | | | Intensity | Yes, but limited | | Position | 2D position | Yes | -- Munzner uses the terms _magnitude channels_ and _identity channels_. --- Ideally, * numeric and ordered attributes should be represented by quantitatively perceived channels; -- * unordered categorical attributes should be represented by non-quantitative channels -- A useful principle: The most important attributes should be mapped to the most effective channels. --- layout: true ## Channel Effectiveness --- Some questions about channels: -- * What kind and how much information can a channel encode? -- * Are some channels better than others? -- * Can channels be used independently, or do they interfere? -- Some criteria for evaluating channels: -- * Accuracy: How well can a viewer decode the information in the channel? -- * Discriminability: How easily can differences between attribute levels be perceived? -- * Separability: Can channels be used independently or is there interference? -- * Popout: can a channel provide popout where a difference is perceived preattentively? -- * Grouping: can a channel show perceptual grouping of items? --- ### Channel Accuracy Stevens (1957) argues that accuracy of magnitude channels can be described by a power law: $$ \text{perceived sensation} = (\text{physical intensity})^\gamma $$ -- Experiments by Stevens suggest these values for some visual channels: .pull-left[ <img src="percep_files/figure-html/unnamed-chunk-26-1.png" style="display: block; margin: auto;" /> ] -- .pull-right[ [Others have raised concerns](https://en.wikipedia.org/wiki/Stevens%27s_power_law) about the validity of these findings. ] <!-- ### Aspect Ratio ```r river <- scan("https://www.stat.uiowa.edu/~luke/data/river.dat") plot(river) ``` **** misleading example from HW2 as slopes --> --- Another approach has used controlled experiments to assess accuracy of various channels used in visualizations: -- * William S. Cleveland and Robert McGill (1984), "Graphical Perception: Theory, Experimentation, and Application to the Development of Graphical Methods," _Journal of the American Statistical Association_ 79, 531–554. -- * William S. Cleveland and Robert McGill (1987), "Graphical Perception: The Visual Decoding of Quantitative Information on Graphical Displays of Data" _Journal of the Royal Statistical Society. Series A_, 192-229. -- * Jeffrey Heer and Michael Bostock (2010) "Crowdsourcing Graphical Perception: Using Mechanical Turk to Assess Visualization Design," _Proceedings of the SIGCHI_, 203-212. --- Munzner's ordering by accuracy: .pull-left.width-60[ <img src="../img/tmmchannels.jpeg" width="2731" style="display: block; margin: auto;" /> ] -- .pull-right.width-30[ This ordering is sometimes referred to as a _perceptual ladder_. <!-- Magnitude Channels (Ordered, Numerical) Identity Channels (Categorical) ---------- ----- Position on common scale Spatial grouping Position on unaligned scale Color hue Length (1D size) Shape Tilt, angle Area (2D size) Depth (3D position) Color luminance, saturation Curvature, volume (3D size) --> {{content}} ] -- Line width is another channel; not sure there is agreement on its accuracy, but it is not high. --- ### Discriminability Many channels, in particular identity channels, can only support a limited number of discriminable levels. -- * Line width is one of the most limited with perhaps 3 levels. -- * Using more than 5 or 6 color hues is not recommended. -- * Similarly, using more than 5 or 6 symbol shapes can create difficulties. -- If the number of levels that can be represented by a channel is smaller than the number of attribute levels then some form of meaningful aggregation is needed. --- ### Separability Some encodings can be used independently of each other; others interfere with each other to some degree. -- <!-- **** something like Munzner Fig 5.10 --> <img src="../img/TMfig5.10.jpg" width="55%" style="display: block; margin: auto;" /> -- * Vertical an horizontal position can be used independently. -- * Color (hue) and position can be used independently -- * Size and hue interfere somewhat; hue is harder to perceive on smaller objects. -- * Width and height do not function well independently; the result is perceived primarily as shape. -- * Encoding two different values in the red and green channels as a hue does not work at all. --- ### Popout Many channels support visual popout: having one item or a few items immediately stand out from the others. -- * Color (hue and intensity) do this well. -- * Shape and size can also be used effectively to create popout. -- Annotation can also be used to create popout. --- ### Grouping Perceptual grouping can be achieved in several ways: .pull-left[ * Using an identity channel to to represent items as a group. * Using _link marks_. * By _enclosure_. * By spatial proximity. ] .pull-right[ <img src="percep_files/figure-html/unnamed-chunk-37-1.png" style="display: block; margin: auto;" /> ] --- layout: true ## Experimental Evidence --- ### Cleveland-McGill The 1984 paper is available from [JSTOR](https://www.jstor.org/stable/2288400). -- The paper formulates a theory for ranking _Elementary Perceptual Tasks_; these correspond to channel mappings. -- Some orderings were addressed by informal experiments (obvious to the authors at least). -- Others were assessed by formal experiments with about 50 subjects. --- Experiments focused on accuracy of decoding, though this is not viewed as the primary purpose of a graph: > One must be careful not to fall into a conceptual trap of adopting > accuracy as a criterion. ... The power of a graph is its ability to > enable one to take in the quantitative information, organize it, and > see patterns and structure not readily revealed by other means of > studying the data. -- Their premise: > A graphical form that involves elementary perceptual tasks that lead > to more accurate judgments than another graphical form (with the > same quantitative information) will result in better organization > and increase the chances of a correct perception of patterns and > behavior." --- The tasks: For each setting -- * Identify which of two marked items is smaller. -- * Estimate the percentage the smaller is of the larger. -- .pull-left[ ![](../img/CM1.jpg) ] -- .pull-right[ ![](../img/CM2.png) ] --- Results: .pull-left[ Percent large errors: ![](../img/CMLE.jpg) ] -- .pull-right[ Absolute error: ![](../img/cleveland-results.png) ] --- ### Heer and Bostock [Heer and Bostock (2010)](http://idl.cs.washington.edu/papers/crowdsourcing-graphical-perception/) set out to replicate the Cleveland McGill experiment using crowd sourcing via [Amazon Mechanical Turk](https://www.mturk.com/) -- They used the five position stimuli from Cleveland and McGill and some new ones: ![](../img/heer-bostock-tasks.png) 50 subjects were recruited for each task. --- Results were consistent with Cleveland-McGill results: ![](../img/HB1.jpeg) Use of Mechanical Turk was deemed a success. --- ### Pie Chart Experiments [Pie charts](https://eagereyes.org/pie-charts) are popular but somewhat controversial. -- * Pie charts are inferior for comparisons to bar charts. -- * Pie charts are quite good at representing part-whole relationships. -- * Cleveland and McGill suggested pie charts are read by angle. -- * [Kosara and Skau](https://eagereyes.org/papers/a-pair-of-pie-chart-papers) report experiments that suggest this is not the case. -- * If it were, [_donut charts_](https://datavizcatalogue.com/methods/donut_chart.html) would be even less effective, but they seem to be very comparable. -- * [Kosara's blog](https://eagereyes.org) provides a [review](https://eagereyes.org/blog/2016/an-illustrated-tour-of-the-pie-chart-study-results) of other pie chart studies. --- layout: true ## Improving Some Common Charts --- Cleveland and McGill set out to suggest improvements to some common charts. This is a selection of their examples. -- ### Dot Charts Cleveland and McGill use their perceptual ladder to argue strongly for using dot charts in place of bar charts and pie charts. --- ### Playfair's Balance of Trade plots Playfair presented a number of plots showing imports and exports between England and other nations. -- A primary goal was to show the balance of trade, the difference between exports and imports: ![](../img/Playfair_Exports_Imports.jpg) --- .pull-left[ Assessing the differences from a plot showing exports and imports as separate curves requires length judgments, which are less accurate than comparisons to a common stale. ] .pull-right[ <!-- data: https://raw.githubusercontent.com/jennybc/r-graph-catalog/master/figures/fig02-14_playfair-s-balance-of-trade-data/fig02-14_playfair-s-balance-of-trade-data.tsv --> <img src="percep_files/figure-html/unnamed-chunk-39-1.png" style="display: block; margin: auto;" /> ] --- .pull-left[ Plotting the difference makes the balance of trade much easier to assess: ] .pull-right[ <img src="percep_files/figure-html/unnamed-chunk-40-1.png" style="display: block; margin: auto;" /> ] --- .pull-left[ An _ensemble plot_ showing both views may also help. ] .pull-right[ <img src="percep_files/figure-html/unnamed-chunk-41-1.png" style="display: block; margin: auto;" /> ] --- ### Framed Unaligned Bars .pull-left[ It is difficult to compare lengths of unaligned rectangles when the lengths are close. <img src="percep_files/figure-html/unnamed-chunk-42-1.png" style="display: block; margin: auto;" /> ] -- .pull-right[ Adding a frame moves the task up the perceptual ladder to an unaligned comparison against a common scale. <img src="percep_files/figure-html/unnamed-chunk-43-1.png" style="display: block; margin: auto;" /> ] --- Comparing to a common scale is still the most effective approach: <img src="percep_files/figure-html/unnamed-chunk-44-1.png" style="display: block; margin: auto;" /> -- But this does suggest that using unaligned framed rectangles to encode a _third_ variable, with position encoding the two primary variables may be effective. --- .pull-left[ ### Framed Rectangle Maps A _choropleth map_ is a common way to depict a quantitative variable in a geographic context. Shading is quite low on the perceptual ladder. Cleveland and McGill suggest the use of framed rectangles positioned on the map as an alternative. This does not seem to have caught on so far, though you do sometimes see the use of other glyphs, such as pie charts. ] .pull-right.width-40[ <!-- ![](http://lh4.ggpht.com/_LenCZlyza20/TR8yaHmsyzI/AAAAAAAAJR8/yTvl7awdkys/tmp14816_thumb1_thumb1.jpg?imgmax=800) --> <img src="../img/CMmap.jpg" width="90%" style="display: block; margin: auto;" /> ] --- layout: true ## Analyzing a Design --- Graph layout involves several levels: -- * Primary data representation * items, attributes * marks, channels -- * Supporting features * trend lines, reference lines, annotations * axes, legends --- A useful structure for describing the primary features: * What are the data items? * What are the attributes? * What marks are used? * What channels are used? * Which attribute is matched to channel 1 * Which attribute is matched to channel 2 * ... -- Useful questions: * Are the most important attributes mapped to the strongest channels? * Do the mappings do a good job of conveying the primary message? * If not, can the graph be improved by adjusting the mappings? --- .pull-left[ ### A Gapminder Plot One of the frames of a plot from the [GapMinder site](https://www.gapminder.org): ![](../img/gapminder2.png) ] -- .pull-right.smaller[ * Items are countries (in a particular year) {{content}} ] -- * Attributes in the plot: * life expectancy * income per person * population * continent * country name * year {{content}} -- * Marks: points (or bubbles). {{content}} -- * Channels and mappings: * horizontal position, mapped to log income * vertical position, mapped to life expectancy * area, mapped to population * color (hue), mapped to continent * interactive: mouse-over, mapped to country name * interactive: time (or frame), mapped to year --- The basic plot can be created with `ggplot` and aesthetic mappings: .pull-left.small-code[ ```r library(gapminder) ggplot(filter(gapminder, year == 2007)) + geom_point(aes(x = gdpPercap, y = lifeExp, size = pop, color = continent)) + scale_x_log10() + ylim(c(20, 85)) ``` ] -- .pull-right[ <img src="percep_files/figure-html/gapminder-basic-1.png" style="display: block; margin: auto;" /> ] -- The data in the `gapminder` package differ somewhat from the data used by the Gapminder site, but overall the plot designs are very close. --- With some adjustments the basic plot can be brought close to the Gapminder version in appearance: .pull-left.tiny-code.width-50[ ```r gm2007 <- filter(gapminder, year == 2007) %>% arrange(desc(pop)) ## sort to avoid over-plotting ggplot(gm2007) + geom_point(aes(x = gdpPercap, y = lifeExp, size = pop, fill = continent), shape = 21) + ## to allow the using `fill` aesthetic scale_x_log10() + ylim(c(20, 85)) + scale_size_area(max_size = 20, labels = comma, breaks = c(0.25 * 10 ^ 9, 0.5 * 10 ^ 9, 10 ^ 9)) + scale_fill_manual(values = c(Africa = "deepskyblue", Asia = "red", Americas = "green", Europe = "gold", Oceania = "brown")) + labs(x = "Income", y = "Life expectancy") + theme(text = element_text(size = 16)) + guides(fill = guide_legend(title = "Continent", override.aes = list(size = 5), order = 1), size = guide_legend(title = "Population", label.hjust = 1, order = 2)) + theme_minimal() + theme(panel.border = element_rect(fill = NA, color = "grey20")) ``` ] .pull-right[ <img src="percep_files/figure-html/gapminder-full-1.png" style="display: block; margin: auto;" /> ] --- Some notes: -- * Using larger bubbles makes the plot more engaging. -- * Using larger bubbles makes differences in population easier to assess, but makes the strength of the relationship between life expectancy and income harder to assess. -- * Using larger bubbles also increases the risk of over-plotting. Sorting the rows so larger bubble are drawn first helps reduce the risk somewhat. -- These plots show a fairly strong marginal association between life expectancy and income. -- There does not seem to be a strong association of population with the other two variables, but these plots are not ideal for that assessment. --- .pull-left.small-code[ To judge the marginal association between life expectancy and population size we can change the channel mapping: {{content}} ] -- * map the horizontal axis to population; * map area to income. {{content}} -- ```r ggplot(filter(gapminder, year == 2007)) + geom_point(aes(x = pop, y = lifeExp, size = gdpPercap)) + scale_x_log10() + ylim(c(20, 85)) + theme_minimal() + theme(panel.border = element_rect(fill = NA, color = "grey20")) ``` -- .pull-right[ <img src="percep_files/figure-html/gapminder-lifepop-1.png" style="display: block; margin: auto;" /> ] -- This confirms that there is very little association between life expectancy and population. -- The association between life expectancy and income is still visible, but is easier to assess when these two variables are mapped to 2D position. --- .pull-left[ ### Michelin Stars This image, from a [blog post](http://createhtml5map.com/interactive-map-blog/interactive-bubble-chart-countries-receive-the-most-michelin-stars-each-year/), shows the total number of stars for different countries: ![](../img/michelin-stars.png) ] -- .pull-right[ * Items: Countries (in a particular year) {{content}} ] -- * Attributes: * country name * number of stars {{content}} -- * Marks: bubbles, text {{content}} -- * Channels and mappings: * bubble color, mapped to country * bubble area, mapped to number of stars * text, mapped to country name (where possible) * text, mapped to number of stars (where possible) --- <!-- separate next line --> .pull-left[ Observations: {{content}} ] -- * None of the channels are very strong. {{content}} -- * The strongest channels, 2D position, are not used. {{content}} -- * The number of colors used is too high. {{content}} -- A simple _dot plot_ would convey the distribution better. {{content}} -- A dot plot using [2017 data](michelin.dat) from an [article](https://www.telegraph.co.uk/travel/maps-and-graphics/map-michelin-star-restaurants-countries-with-the-most/) in The Telegraph: -- .pull-right[ .hide-code[ ```r michelin <- read.table(WLNK("michelin.dat"), head = TRUE) michelin <- mutate(michelin, stars = one + 2 * two + 3 * three, country = reorder(country, stars)) ggplot(michelin, aes(x = stars, y = country)) + geom_point() + labs(x = "Stars", y = NULL) + theme_minimal() + theme(text = element_text(size = 16)) + theme(panel.border = element_rect(fill = NA, color = "grey20")) ``` <img src="percep_files/figure-html/unnamed-chunk-46-1.png" style="display: block; margin: auto;" /> ] ] --- .pull-left[ Even if a bubble plot is desired for aesthetic reasons, position could be used to * group countries by continent; * show countries on a map. {{content}} ] -- A plot like the original can be constructed by * computing locations for a set of packed spheres with specified radii; * using `geom_point` and `geom_text`. -- .pull-right.small-code.scroll-box-20[ .hide-code[ ```r ## create randomly located packed spheres with specified areas library(packcircles) set.seed(54321) packing <- circleProgressiveLayout(michelin$stars) ## merge circle locations with starts data mcirc <- bind_cols(packing, michelin) %>% mutate(country = factor(country)) ## clean out stray attributes ## compute some colors to use nr <- nrow(mcirc) pal <- colorRampPalette(RColorBrewer::brewer.pal(9, "Set1")) cols <- sample(pal(nr), nr) ## these need tuning for the screen or R markdown csize <- 45 tsize <- 2.5 ## the basic plot ## uses shape = 19 and `color` aesthetic p <- ggplot(mcirc, aes(x = x, y = y)) + geom_point(aes(size = radius ^ 2, color = country), shape = 19) + scale_size_area(max_size = csize) + geom_text(aes(label = paste(country, stars, sep = "\n")), data = filter(mcirc, stars >= 120), size = tsize) + coord_fixed() ## adjustments p + guides(size = "none") + scale_color_manual(values = cols) + xlim(with(mcirc, range(x) + c(-1, 1) * max(radius))) + ylim(with(mcirc, range(y) + c(-1, 1) * max(radius))) + theme_void() ``` <img src="percep_files/figure-html/unnamed-chunk-47-1.png" style="display: block; margin: auto;" /> ] ] --- .pull-left[ A somewhat more robust approach * creates vertex data for polygon approximations to the circles; * merges the stars data with the polygon data; * uses `geom_polygon` and `geom_text`. {{content}} ] -- This is very similar to the way simple _choropleth maps_ are created. -- .pull-right.small-code.scroll-box-20[ .hide-code[ ```r ## compute polygon approximations to spheres mcircpoly <- circleLayoutVertices(mcirc, idcol = "country", npoints = 100) %>% rename(country = id) ## merge the stars data into the polygon data sttab <- select(michelin, country, stars) mcircpoly <- left_join(mcircpoly, sttab, "country") ## create the plot ggplot(mcircpoly, aes(x = x, y = y)) + geom_polygon(aes(fill = country)) + geom_text(aes(label = paste(country, stars, sep = "\n")), data = filter(mcirc, stars >= 120), size = tsize) + coord_fixed() + scale_fill_manual(values = cols) + theme_void() ``` <img src="percep_files/figure-html/unnamed-chunk-48-1.png" style="display: block; margin: auto;" /> ] ] --- layout: true ## Aspect Ratio and Perception --- The river flow data shows how important aspect ratio can be to our ability to detect patterns: <img src="percep_files/figure-html/unnamed-chunk-49-1.png" style="display: block; margin: auto;" /> --- .pull-left[ Using a line plot the basic periodicity becomes apparent even in the first aspect ratio. .hide-code[ ```r p2 <- p0 + geom_line() p2 + coord_fixed(ratio = 35) ``` <img src="percep_files/figure-html/unnamed-chunk-50-1.png" style="display: block; margin: auto;" /> ] ] -- .pull-right[ But the steeper increase/shallower decrease of most periods is easier to see in the second aspect ratio: .hide-code[ ```r p2 + coord_fixed(ratio = 4) ``` <img src="percep_files/figure-html/unnamed-chunk-51-1.png" style="display: block; margin: auto;" /> ] ] --- The aspect ratio also influences interpretation of results. -- Some alternative views of (suspect) data on the number of people on government assistance over a time period: .hide-code[ ```r library(readr) w <- read_csv(WLNK("hw2-welfare.csv")) w <- mutate(w, onAssistance = onAssistance / 10 ^ 6) w <- mutate(w, date = seq(as.Date("2009-01-01"), by = "quarter", length.out = 10)) p0 <- ggplot(w, aes(x = date, y = onAssistance)) + theme_minimal() + theme(panel.border = element_rect(fill = NA, color = "grey20")) p1 <- p0 + geom_line(aes(group = 1)) grid.arrange(p1, p1 + coord_fixed(ratio = 8), p1 + ylim(0, max(w$onAssistance)), p0 + geom_col(width = 40), ncol = 2) ``` <img src="percep_files/figure-html/unnamed-chunk-52-1.png" style="display: block; margin: auto;" /> ] --- Some notes: -- * Automated choices of axis scaling can affect the aspect ratio of the content of a plot. -- * A zero base line supports ratio comparisons. -- * The preattentive response to bar charts is always to compare ratios, so using a zero base line is important. -- * Using a non-zero base line for line plots and scatter plots encourages interval, or difference, comparisons. -- * Research on the effect of aspact ratio on perception has focused on accuracy of slope comparisons. -- * The general message is that keeping away from slopes that are too steep or too shallow is best. -- * _Banking to 45 degrees_, or choosing an aspect ratio so the slope magnitudes are distributed around 45 degrees is often recommended. -- * This also tends to be a useful "neutral ground" when political implications are involved. --- Some references: * A [blog post](https://eagereyes.org/basics/banking-45-degrees) by Robert Kosara. -- * William S. Cleveland, Marylyn E. McGill and Robert McGill (1988), "The Shape Parameter of a Two-Variable Graph", _Journal of the American Statistical Association_ ([JSTOR](http://www.jstor.org/stable/2288843?seq=1#page_scan_tab_contents)) -- * Justin Talbot, John Gerth, Pat Hanrahan (2012), "An Empirical Model of Slope Ratio Comparisons", _IEEE Trans. Visualization & Comp. Graphics (Proc. InfoVis)_ ([PDF](http://vis.stanford.edu/files/2012-SlopeComparison-InfoVis.pdf)) <!-- Check this out: http://timelyportfolio.github.io/buildingwidgets/week11/example_07.html --> <!-- More from here: http://enrico.bertini.io/teaching/ --> --- layout: true ## Ensemble Plots and Faceting --- Using multiple channels allows a single plot to show a lot of information. -- But over-plotting and interference can become problems. -- One alternative is to use several related views in a useful arrangement. -- Such arrangements are sometimes called _ensemble plots_. -- There are a number of variations; a few are introduced below. --- ### Similar Plots with Different Variables and Shared Encodings One way to show three continuous variables is with two plots that share an axis: .hide-code[ ```r library(patchwork) pe_thm <- theme_minimal() + theme(panel.background = element_rect(color = "black", linewidth = 0.5, fill = NA)) p1 <- ggplot(gm2007, aes(x = gdpPercap, y = lifeExp, color = continent)) + geom_point() + scale_x_log10() + guides(color = "none") + pe_thm p2 <- ggplot(gm2007, aes(x = pop / 10 ^ 6, y = lifeExp, color = continent)) + geom_point() + scale_x_log10() + pe_thm + theme(axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank()) p1 + p2 ``` <img src="percep_files/figure-html/unnamed-chunk-53-1.png" style="display: block; margin: auto;" /> ] -- Life expectancy is mapped to the vertical position in both plots. -- Continent is mapped to color in both plots. -- Guides can be shared when encodings are shared. --- ### Different Plots with Shared Encodings Multiple views of the data are often helpful. -- Sharing encodings makes the relations between views easier to perceive. -- .hide-code[ ```r p3 <- ggplot(gm2007, aes(x = pop / 10 ^ 6, y = reorder(continent, pop, FUN = sum), fill = continent)) + geom_col() + ylab(NULL) + pe_thm p1 + p3 ``` <img src="percep_files/figure-html/unnamed-chunk-54-1.png" style="display: block; margin: auto;" /> ] --- ### Small Multiples .pull-left.width-40[ _Small multiples_ refers to a collection of plots with identical structure showing different subsets of the data and organized in a useful way. {{content}} ] -- These plot collections are also called _trellis plots_, _lattice plots_, or _faceted plots_. {{content}} -- A plot of life expectancy against income per capita in 2007 faceted by continent: -- .pull-right.width-60[ .hide-code[ ```r gd <- filter(gapminder, year %in% c(1977, 1987, 1997, 2007)) gd2007 <- filter(gapminder, year == 2007) fct_thm <- theme_minimal() + theme(panel.background = element_rect(color = "black", linewidth = 0.5, fill = NA)) ggplot(gd2007, aes(x = gdpPercap, y = lifeExp, color = continent)) + geom_point(size = 2.5) + scale_x_log10() + facet_wrap(~ continent) + fct_thm ``` <img src="percep_files/figure-html/unnamed-chunk-55-1.png" style="display: block; margin: auto;" /> ] ] --- A useful variation is to show a muted view of the full data in the background: .hide-code[ ```r ggplot(gd2007, aes(x = gdpPercap, y = lifeExp, color = continent)) + geom_point(data = mutate(gd2007, continent = NULL), color = "grey80") + geom_point(size = 2.5) + scale_x_log10() + facet_wrap(~ continent) + fct_thm ``` <img src="percep_files/figure-html/unnamed-chunk-56-1.png" style="display: block; margin: auto;" /> ] --- .pull-left.width-40[ Data can be facetet on two variables. This plot shows the full data faceted by both continent and a set of years: ] .pull-right.width-60[ .hide-code[ ```r ggplot(gd, aes(x = gdpPercap, y = lifeExp, color = continent)) + geom_point(size = 2.5) + scale_x_log10() + facet_grid(continent ~ year) + fct_thm ``` <img src="percep_files/figure-html/unnamed-chunk-57-1.png" style="display: block; margin: auto;" /> ] ] --- .pull-left.width-40[ Adding muted data for each year helps regonizing where each continent group fits within a year ] .pull-right.width-60[ .hide-code[ ```r ggplot(gd, aes(x = gdpPercap, y = lifeExp, color = continent)) + geom_point(data = mutate(gd, continent = NULL), color = "grey80") + geom_point(size = 2.5) + scale_x_log10() + facet_grid(continent ~ year) + fct_thm ``` <img src="percep_files/figure-html/unnamed-chunk-58-1.png" style="display: block; margin: auto;" /> ] ] --- layout: false ## Reading Section [_Perception and Data Visualization_](https://socviz.co/lookatdata.html#perception-and-data-visualization) in [_Data Visualization_](https://socviz.co/). Chapter [_Data visualization principles_](https://rafalab.dfci.harvard.edu/dsbook/data-visualization-principles.html) in [_Introduction to Data Science Data Analysis and Prediction Algorithms with R_](https://rafalab.dfci.harvard.edu/dsbook/). --- ## Exercises 1) Which of the following channels are magnitude channels and which are identity channels? * a. Position on a common scale * b. Length * c. Color hue (red, green, etc.) * d. Symbol shape (dot, cross, etc.) --- 2) Consider the following visualizations of the 2017 Michelin star data: <img src="percep_files/figure-html/unnamed-chunk-60-1.png" style="display: block; margin: auto;" /> Which plot makes it easier to compare the numbers of stars for different countries? Explain your conclusion by identifying the channels used and their relative strengths. --- 3) Identify the items, attributes, marks, channels, and mappings use in the following plot: <img src="percep_files/figure-html/unnamed-chunk-61-1.png" style="display: block; margin: auto;" />
//adapted from Emi Tanaka's gist at //https://gist.github.com/emitanaka/eaa258bb8471c041797ff377704c8505