By Bluecology blog

## Data visuals: notes for my talks in 2017

Supplementary notes for CJ Brown’s talks on dataviz in 2017 for Griffith

University’s honours students and the UQ Winterschool in

Bioinformatics.

### Visualsing sexual dimorphism in elephant seals

I picked this example to demonstrate a simple barchart for representing

the sizes of different things.

## Comparing volume and area

Compare these. Note that if we compare circles we should use area, not

the radius or diameter to scale their size.

### Exploration of data

Let’s create a point cloud to demonstrate some data exploration

techniques

Can’t see alot here. A linear model might help us explore if there is

any trend going on:

What about identifying extreme points, that may be worth investigating

further? We can pick out points that are greater than 2SDs from the

trend:

```
modresid sd2)
plot(x,y, pch = 16, col = grey(0.5,0.5), las = 1)
abline(mod1, lwd = 2, col = 'red')
points(x[ipt], y[ipt], pch = 16, col = rgb(1,0,0, 0.6))
```

### Three ways of visualising the same x-y data

Each of these graphs of the same data has a slightly different

interpretation.

```
library(MASS)
filled.contour(kde2d(x,y), scale = F)
```

```
plot(x,y, pch = 16, col = grey(0.5, 0.5))
abline(mod1, lwd = 3, col = 'red')
```

### Make your own Datasaurus dozen

The datasaurus is a great example of why you should view your data,

invented by Alberto Cairo. See Steph Locke’s code and package on

github for making this in R.

```
library(datasauRus)
datnames
```

Convince yourself that the mean, sd and correlation is the same in all

of these plots:

```
library(dplyr)
datasaurus_dozen %>% group_by(dataset) %>%
summarize(meanx = mean(x), meany = mean(y),
sdx = sd(x), sdy = sd(y),
corr = cor(x,y))
## # A tibble: 13 × 6
## dataset meanx meany sdx sdy corr
##
## 1 away 54.26610 47.83472 16.76982 26.93974 -0.06412835
## 2 bullseye 54.26873 47.83082 16.76924 26.93573 -0.06858639
## 3 circle 54.26732 47.83772 16.76001 26.93004 -0.06834336
## 4 dino 54.26327 47.83225 16.76514 26.93540 -0.06447185
## 5 dots 54.26030 47.83983 16.76774 26.93019 -0.06034144
## 6 h_lines 54.26144 47.83025 16.76590 26.93988 -0.06171484
## 7 high_lines 54.26881 47.83545 16.76670 26.94000 -0.06850422
## 8 slant_down 54.26785 47.83590 16.76676 26.93610 -0.06897974
## 9 slant_up 54.26588 47.83150 16.76885 26.93861 -0.06860921
## 10 star 54.26734 47.83955 16.76896 26.93027 -0.06296110
## 11 v_lines 54.26993 47.83699 16.76996 26.93768 -0.06944557
## 12 wide_lines 54.26692 47.83160 16.77000 26.93790 -0.06657523
## 13 x_shape 54.26015 47.83972 16.76996 26.93000 -0.06558334
```

We can also save these as .png images to make a .gif image (see also

here)

```
for (ilvs in 1:nlevels){
i
```

### Effect size

When doing confirmatory analysis, we might want to know how strong an

effect is. Data viz is very useful for this task. Lets compare two

datasets that have similar p-values, but very different effect sizes

```
set.seed(42)
x |t|)
## (Intercept) 2.8054 0.4614 6.080 1.71e-09 ***
## x 4.2096 0.4603 9.145 |t|)
## (Intercept) 2.98703 0.03076 97.11
```

### Don’t waste digital ink

Plots with less ‘add-ons’ tend to communicate the key message more

clearly. For instance, just like excel plots dont:

You can get additional themes for ggplot2 using this excellent

package.

A cleaner view:

```
ggplot(dat, aes(x = x, y = y)) + geom_point() +
theme_base()
```

Or simply:

```
plot(dat$x, dat$y, xlab = "x", ylab = "y", las = 1)
```

A good principle is to not use ‘ink’ on figures that isn’t needed to

communicate your message. Tufte

takes the ‘less ink’ philosophy to the extreme:

```
ggplot(dat, aes(x = x, y = y)) + geom_point() +
theme_tufte()+theme(axis.text=element_text(size=20),
axis.title=element_text(size=20))
```

### When is ggplot2 appropriate, or when should I use base R?

In general I think ggplot2 is appropriate for

problems of intermediate complexity. Like this:

Base R is great if you just want to plot a barplot quickly, or do an x-y

plot. ggplot2 comes into its own for slight more complex plots, like

having multiple panels for different groups or colouring lines by a 3rd

factor. But once you move to really complex plots, like overlaying a

subplot on a map, ggplot2 becomes very difficult, if not impossible. At

that point it is better to move back to Base R. ggplot2 can also get

very fiddly if you are very specific about your plots, like having

certain colours, or the labels in a certain way.

As an example, ggplot2 is great for data like this:

It is also pretty handy for faceting:

```
ggplot(dat, aes(x = x1, y = y1)) +
geom_point() + facet_wrap(~grps)+
theme_bw()
```

The key with ggplot2 is to have your data in a data-frame.

In reality both ggplot2 and base R graphics are worth learning, but I

would start with learning the basics of base R graphics and then move

onto ggplot2 if you want to quickly plot lots of structured data-sets.

### Pie graphs vs bar graphs

In Mariani et al. they plot rates of seafood fraud by several European

countries. While its a foundational study that establishes improvement

in the accuracy of food labelling, their graphics could be improved in

several ways.

First they use perspective pies. This makes it incredibly hard to

compare the two groups (fish that are labelled/mislabelled). Humans are

very bad at comparing angles and pretty bad at comparing areas. With the

perspective you can’t even compare the areas properly. They do provide

the raw numbers, but then, why bother with the pies?

Note that the % pies misrepresent the data slightly because the %

figures are actually odds ratios (mis-labels / correct labels), rather

than percent (mis-labeels / total samples).

Second the pies are coloured red/green, which will be hard for red-green

colourblind people to see.

Third, they have coloured land blue on their map, so it appears to be

ocean at first look.

Fourth, the map is not really neccessary. There are no spatial patterns

going on that the authors want to draw attention to. I guess having a

map does emphasize that the study is in Europe. Finally, the size of

each pie is scaled to the sample size, but the scale bar for the sample

size shows a sample of only 30, whereas most of their data are for much

larger samples sizes (>200). Do you get the impression from the pies

that the UK has 668 samples, whereas Ireland only has 187? Therefore,

from this graphic we have no idea what sample size was used in each

country.

In fact, all the numbers that are difficult to interpret in the figure

are very nicely presented in Table 1.

Below is a start at improving the presentation. For instance, you could

do a simple bar chart, ordering by rate of mislabelling.

You could add another subfigure to this, showing the rate by different

species too.

The barplot doesn’t communicate the sample size, but then that is

probably not the main point. The sample sizes are probably best reported

in the table

If we felt the map was essential, then putting barcharts on it would be

more informative. It is not that easy to add barcharts ontop of an

existing map in R, so I would recommend creating the barcharts

seperately, then adding them on in Illustrator or Powerpoint.

We can make a basic map like this:

```
library(maps)
library(maptools)
map('world', xlim = c(-20, 20), ylim = c(35, 60), col = 'grey', fill = T)
```

Then create some nice barcharts. We write a loop so we get one barchart

for each country.

### Choosing axes

It can be misleading to present % and proportion data on axes that are

not scaled 0 – 100%. For instance, compare these three graphs:

### Choosing colour scales

Alot of thought should go into choosing colour scales for graphs for

instance- will it print ok? will colour blind people be able to see

this? does the scale create artificial visual breaks in the data?

Luckily there is a package to help you make the right decision for a

colour scale, it is called `RColorBrewer`

. Check out colorbrewer.org for

a helpful interactive web interface for choosing colours.

Here I recreate the map of that in Cinner et al. 2016 Nature for fish

biomass (using dummy data, as I don’t have their data).

First let’s specify some dummy data

Using red-green palettes makes it hard for colour blind people. Also,

using a diverging palette makes it look like there is something

important about the middle point (yellow). A better palette to use would

be one of the sequential ones. Using reds (and reversing it using

`rev()`

) emphasises the worst places. We could use greens and emphasise

the best places too. I am using a light grey for the fill so that the

points stand out more.

```
#Create sequential colours for locations
cols
```

To make it easier to understand, let’s look at these again as contour

plots. I will use a more appropriate diverging palette to the red-green

one though.

```
filled.contour(z, col = brewer.pal(9, 'RdBu'), nlevels = 10)
```

Notice the diverging pallette creates an artificial split at yellow

One of the only legitimate uses for pie graphs (I think) is visualising

the colour scales. Here is how:

### Interpreting rates

People are bad at interpreting rates, we just can’t get our heads around

accumulation very well. Here is a numerical example. Check out the below

figure and ask yourself:

At what time is the number of people in the shopping centre declining?

Would you say it is at point A, B, C or D?

Before you proceed with code below, take the poll:

Loading poll…

Here is how we made the figure and generated the data:

```
par(mar = c(4,4.5,2,2), mgp = c(3,1,0))
plot(times, inrate_err, type = 'l', xlab = 'Hour of day', ylab = 'People per 10 minutes', las = 1, cex.axis = 2, lwd = 3, col = 'darkblue', cex.lab = 2, ylim = c(0, 12))
lines(times, outrate_err, lwd = 3, col = 'tomato')
abline(v = 12, lwd = 2, col = grey(0.5,0.5))
text(12, 13, 'A', xpd = NA, cex = 2)
abline(v = 13.5, lwd = 2, col = grey(0.5,0.5))
text(13.5, 13, 'B', xpd = NA, cex = 2)
abline(v = 14.2, lwd = 2, col = grey(0.5,0.5))
text(14.2, 13, 'C', xpd = NA, cex = 2)
abline(v = 15.8, lwd = 2, col = grey(0.5,0.5))
text(15.8, 13, 'D', xpd = NA, cex = 2)
legend('bottomleft', legend = c('Entering', 'Leaving'), lwd = 2, col = c('darkblue','tomato'), cex = 1.5, xpd = NA)
```

Let’s plot the total number of people:

```
par(mar = c(5,5.5,2,2), mgp = c(4,1,0))
plot(times, cumsum(inrate_err) - cumsum(outrate_err), type = 'l', xlab = 'Hour of day', ylab = 'People in shopping centre', las = 1, cex.axis = 2, lwd = 3, col = 'darkblue', cex.lab = 2, ylim = c(0, 120))
abline(v = 12, lwd = 2, col = grey(0.5,0.5))
text(12, 130, 'A', xpd = NA, cex = 2)
abline(v = 13.5, lwd = 2, col = grey(0.5,0.5))
text(13.5, 130, 'B', xpd = NA, cex = 2)
abline(v = 14.1, lwd = 2, col = 'tomato')
text(14.2, 130, 'C', xpd = NA, cex = 2)
abline(v = 15.8, lwd = 2, col = grey(0.5,0.5))
text(15.8, 130, 'D', xpd = NA, cex = 2)
```

Hopefully the answer is obvious now. So the right scales can help make

interpretation much easier.

### Anatomy of a simple chart

The construction of a simple chart in R can be a surprisingly long piece

of code. Here is an example to get you started. Don’t be afraid to

experiment!

```
# --------------- #
# Make some data
# --------------- #
set.seed(42)
n
```

Which look terrible. Let’s build a better chart.

```
# Package for colours
library(RColorBrewer)
#Set axis limits
ymax
```

## Resources and further reading

To

**leave a comment** for the author, please follow the link and comment on their blog:

** Bluecology blog**.

R-bloggers.com offers

**daily e-mail updates** about

R news and

tutorials on topics such as:

Data science,

Big Data, R jobs, visualization (

ggplot2,

Boxplots,

maps,

animation), programming (

RStudio,

Sweave,

LaTeX,

SQL,

Eclipse,

git,

hadoop,

Web Scraping) statistics (

regression,

PCA,

time series,

trading) and more…

Source:: R News

## Recent Comments